Skip to content

Instantly share code, notes, and snippets.

@loosechainsaw
Created August 21, 2012 13:55
Show Gist options
  • Save loosechainsaw/3415669 to your computer and use it in GitHub Desktop.
Save loosechainsaw/3415669 to your computer and use it in GitHub Desktop.
Auditing Interceptor Example
using System;
using System.Linq;
using System.Reflection;
using Castle.Core;
using Castle.DynamicProxy;
using Castle.MicroKernel.Proxy;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
namespace WindsorExamples
{
[AttributeUsage(AttributeTargets.Method)]
public class AuditAttribute : Attribute
{
public string Message { get; set; }
public AuditAttribute(string message)
{
Message = message;
}
}
public interface ICustomerService
{
void DeleteStaleCustomer();
}
public class CustomerService : ICustomerService
{
[Audit("Audit of delete customers which are stale")]
public void DeleteStaleCustomer()
{
Console.WriteLine("Deleting stale customers");
}
}
public class AuditInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var attribute = invocation.MethodInvocationTarget.GetCustomAttribute(typeof(AuditAttribute),false);
if (attribute != null)
Console.WriteLine(attribute.As<AuditAttribute>().Message);
invocation.Proceed();
}
}
public class AuditInterceptorSelector : IModelInterceptorsSelector
{
public bool HasInterceptors(ComponentModel model)
{
var result = model.Implementation.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Any(method => method.GetCustomAttributes(false).Any(attribute=> attribute.GetType() == typeof (AuditAttribute)));
return result;
}
public InterceptorReference[] SelectInterceptors(ComponentModel model, InterceptorReference[] interceptors)
{
return new[]
{
InterceptorReference.ForType<AuditInterceptor>()
};
}
}
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.Kernel.ProxyFactory.AddInterceptorSelector(new AuditInterceptorSelector());
container.Register(Component.For<AuditInterceptor>());
container.Register(Component.For<ICustomerService>().ImplementedBy<CustomerService>().LifeStyle.Singleton);
var element = container.Resolve<ICustomerService>();
element.DeleteStaleCustomer();
}
}
public static class ExtensionMethods
{
public static T As<T>(this object o)
{
return (T)o;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment