I was using Castle Windsor to manipulate registrations. For instance, Windsor's Kernal has an event, named ComponentRegistered, where I can register to that event and add an interceptor to the service if given service/component has a specific attribute. Example:
handler.ComponentModel
.Interceptors.Add(new InterceptorReference(typeof(UnitOfWorkInterceptor)));
I can do that conditional by checking handler.ComponentModel.Implementation type.
I'm looking a similar hook in Autofac but could not find it.
You can do the same thing using Module
and the AttachToComponentRegistration
method. This method will be fired for each registration (present and future).
public class InterceptorModule : Module
{
protected override void AttachToComponentRegistration(
IComponentRegistry componentRegistry, IComponentRegistration registration)
{
registration.Activating += (sender, e) =>
{
if (e.Component.Services.Any<IService>())
{
e.ReplaceInstance(...);
}
};
base.AttachToComponentRegistration(componentRegistry, registration);
}
}
You will have to register this module in Autofac like this :
builder.RegisterModule(new InterceptorModule());
You can also use the native castle plugin :
var builder = new ContainerBuilder();
builder.RegisterType<SomeType>()
.As<ISomeInterface>()
.EnableInterfaceInterceptors();
builder.Register(c => new CallLogger(Console.Out));
var container = builder.Build();
var willBeIntercepted = container.Resolve<ISomeInterface>();
See Interceptors from the Autofac documentation for more information
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.