Created
August 21, 2012 13:55
-
-
Save loosechainsaw/3415669 to your computer and use it in GitHub Desktop.
Auditing Interceptor Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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