Skip to content

Instantly share code, notes, and snippets.

@loosechainsaw
Created August 28, 2012 14:15
Show Gist options
  • Save loosechainsaw/3498391 to your computer and use it in GitHub Desktop.
Save loosechainsaw/3498391 to your computer and use it in GitHub Desktop.
Container with Dynamic Proxy Fruit
using System;
using System.Reflection;
using Castle.Core;
using Castle.DynamicProxy;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
namespace DpWorkshop
{
public class Person
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class AuditingInterceptor : IInterceptor
{
public int Count { get; private set; }
public void Intercept(IInvocation invocation)
{
Console.WriteLine("Invoking: {0}",invocation.Method.Name);
invocation.Proceed();
Console.WriteLine("Invoked: {0}", invocation.Method.Name);
}
}
public class AuditingProxyGenerationHook : IProxyGenerationHook
{
public AuditingProxyGenerationHook()
{
}
public void MethodsInspected()
{
}
public void NonProxyableMemberNotification(Type type, MemberInfo memberInfo)
{
Console.WriteLine("Can not proxy method: {0}", memberInfo.Name);
}
public bool ShouldInterceptMethod(Type type, MethodInfo methodInfo)
{
return methodInfo.Name.StartsWith("Call");
}
}
public class AuditingProxyInterceptorSelector : IInterceptorSelector
{
public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
{
if(method.Name.StartsWith("Call"))
return new IInterceptor[]{ new AuditingInterceptor()};
return null;
}
}
public interface IService
{
void Call1();
void Call2();
void Poke();
}
public class Service : IService
{
public void Call1()
{
Console.WriteLine("Call1");
}
public void Call2()
{
Console.WriteLine("Call2");
}
public void Poke()
{
Console.WriteLine("Poke");
}
}
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.Register(Component.For<AuditingInterceptor>().LifestyleSingleton());
container.Register(
Component.For<IService>().ImplementedBy<Service>().LifestyleTransient().Interceptors(
InterceptorReference.ForType<AuditingInterceptor>()).SelectedWith(new AuditingProxyInterceptorSelector()).Anywhere.Proxy.Hook(new AuditingProxyGenerationHook()));
var comp = container.Resolve<IService>();
comp.Call1();
comp.Call2();
comp.Poke();
Console.WriteLine("Press any key to exit....");
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment