Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac, how to intercept the service with an instance of a Aspect but not with the Type of Aspect?

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!

like image 985
Maris Avatar asked Apr 29 '13 10:04

Maris


Video Answer


1 Answers

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.

like image 70
Travis Illig Avatar answered Nov 14 '22 15:11

Travis Illig