Skip to content

Instantly share code, notes, and snippets.

@Hereigo
Last active December 14, 2018 09:00
Show Gist options
  • Save Hereigo/a580e662d687c02f8a7605041c40fcbd to your computer and use it in GitHub Desktop.
Save Hereigo/a580e662d687c02f8a7605041c40fcbd to your computer and use it in GitHub Desktop.
Castle.DynamicProxy_Example
using System;
using System.Collections.Generic;
using Castle.Core;
using Castle.Core.Interceptor;
using Castle.DynamicProxy;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
namespace Console_CastleDynamicProxy
{
class Program
{
static void Main()
{
WindsorContainer container = new WindsorContainer();
container.Register(Component.For<LoggingInterceptor>().LifeStyle.Singleton);
container.Register(Component.For<IMyTest>().ImplementedBy<MyTest>().Interceptors(typeof(LoggingInterceptor)));
IMyTest myTest = container.Resolve<IMyTest>();
myTest.AMethod(3.1415926535); // to interface (interceptor!)
}
}
public class MyTest : IMyTest
{
public double AMethod(double a) { return a * 2; }
}
public interface IMyTest
{
double AMethod(double a);
}
public class LoggingInterceptor : IInterceptor, IOnBehalfAware
{
private string _entityName;
public void Intercept(IInvocation invocation)
{
List<string> largs = new List<string>(invocation.Arguments.Length);
for (int i = 0; i < invocation.Arguments.Length; i++)
largs.Add(invocation.Arguments[i].ToString());
string args = largs.Count == 0 ? "[no arguments]" : string.Join(", ", largs.ToArray());
string method = invocation.Method == null ? "[on interface target]" : invocation.Method.Name;
Console.WriteLine(string.Format("{0}.{1} called with arguments {2}", _entityName, method, args));
invocation.Proceed(); // AMethod execution
Console.WriteLine(string.Format("After invocation. Return value {0}", invocation.ReturnValue));
}
public void SetInterceptedComponentModel(ComponentModel target)
{
if (target != null)
_entityName = target.Implementation.FullName;
// _entityName = namespace.Class (invocation.TargetType.FullName)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment