I have an Autofac
as an IoC container. I want to register Aspect for the some types. I can do it like this:
build.RegisterType(myType).As(ImyType).EnableInterfaceInterceptors().InterceptedBy(typeof(Aspect));
But what if I need to register the interceptor to the some amount of classes using not a Type of interceptor but it's instance. Lets look how I think it should look like:
Aspect aspectInstance = new Aspect("some data to constructor")
build.RegisterType(myType).As(ImyType).EnableInterfaceInterceptors().InterceptedBy(aspectInstance);
I was doing so using Ninject IoC. but what about Autofac? Thx for any advance!
Check out the Autofac wiki page on Autofac.Extras.DynamicProxy2. It shows an example of a CallLogger
interceptor where it registers a lambda as the interceptor:
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>();
For your case, just switch it to register an instance.
var builder = new ContainerBuilder();
builder.RegisterType<SomeType>()
.As<ISomeInterface>()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(Aspect));
var interceptor = new Aspect();
builder.RegisterInstance(interceptor);
var container = builder.Build();
var willBeIntercepted = container.Resolve<ISomeInterface>();
Alternatively, you can use named interceptors if you don't want your aspect to be typed.
var builder = new ContainerBuilder();
builder.RegisterType<SomeType>()
.As<ISomeInterface>()
.EnableInterfaceInterceptors()
.InterceptedBy("my-aspect-instance");
var interceptor = new Aspect();
builder.RegisterInstance(interceptor)
.Named<IInterceptor>("my-aspect-instance");
var container = builder.Build();
var willBeIntercepted = container.Resolve<ISomeInterface>();
Again, check out the wiki - there are lots of ways to associate the interceptor with the class being intercepted, including named, typed, attributes... lots of samples on the wiki.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With