Set Default Interceptor Unity Extension
With Unity, it is quite easy to implement an extension that automatically sets the appropriate interceptor for each registered type.
Here is how I did it:
public
class DefaultInterceptorInterceptionExtension : Interception{
private static readonly IInterceptor [] interceptors = null; static DefaultInterceptorInterceptionExtension(){
interceptors = (
from interceptorType in (from type in typeof(IInterceptor).Assembly.GetExportedTypes() where typeof(IInterceptor).IsAssignableFrom(type) && type.IsAbstract == false &&type.IsInterface ==
false select type) select Activator.CreateInstance(interceptorType) as IInterceptor).ToArray();}
protected override void Initialize(){
base.Initialize(); IConfigurationSource configSource = ConfigurationSourceFactory.Create(); PolicyInjectionSettings section = configSource.GetSection(PolicyInjectionSettings.SectionName) as PolicyInjectionSettings; if (section != null){
section.ConfigureContainer(this.Container, configSource);}
this.Context.Registering += new EventHandler<RegisterEventArgs>(
delegate(Object sender, RegisterEventArgs e){
this.setInterceptorFor(e.TypeFrom, e.TypeTo, e.Name);}
);
this.Context.RegisteringInstance += new EventHandler<RegisterInstanceEventArgs>(
delegate(Object sender, RegisterInstanceEventArgs e){
this.setInterceptorFor(e.RegisteredType, e.Instance.GetType(), e.Name);}
);
}
private void setInterceptorFor(Type typeToIntercept, Type typeOfInstance, String name){
foreach (IInterceptor interceptor in interceptors){
if ((interceptor.CanIntercept(typeToIntercept) == true) && (interceptor.GetInterceptableMethods(typeToIntercept, typeOfInstance).Count() != 0)){
if (interceptor is IInstanceInterceptor){
this.Container.Configure<Interception>().SetDefaultInterceptorFor(typeToIntercept, interceptor as IInstanceInterceptor);}
else if (interceptor is ITypeInterceptor){
this.Container.Configure<Interception>().SetDefaultInterceptorFor(typeToIntercept, interceptor as ITypeInterceptor);}
break;}
}
}
}
And you register with like this:
<unity><
typeAliases> <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /><
typeAlias alias="transient" type="Microsoft.Practices.Unity.TransientLifetimeManager, Microsoft.Practices.Unity, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <typeAlias alias="external" type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager, Microsoft.Practices.Unity, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /><
typeAlias alias="thread" type="Microsoft.Practices.Unity.PerThreadLifetimeManager, Microsoft.Practices.Unity, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> </typeAliases><
containers> <container><
extensions> <add type="DefaultInterceptorInterceptionExtension, SomeAssembly" /></
extensions></container>
</containers><unity>