Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Autofac Interface Interception with IAsyncInterceptor

I did use this documentation: https://autofaccn.readthedocs.io/en/latest/advanced/interceptors.html

to implement Interface Interceptors. To handle my async calls I used the IAsyncInterceptor interface described here:

https://github.com/JSkimming/Castle.Core.AsyncInterceptor

The registration code I came up with does look like this:

 builder.Register(c => new CallResultLoggerInterceptor())
    .Named<IAsyncInterceptor>("log-calls");

  builder.RegisterType<AppointmentService>()
    .As<IAppointmentService>()
    .EnableInterfaceInterceptors()
    .InstancePerDependency();

where the AppointmentService has an InterceptAttribute.

 [Intercept("log-calls")]
 public class AppointmentService : IAppointmentService
 ...

When i call the containers Build() method, it throws an ComponentNotRegisteredException with the message:

The requested service 'log-calls (Castle.DynamicProxy.IInterceptor)' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

which is correct because I do not implement IInterceptor but IAsyncInterceptor. I guess the problem is the concrete implementation of EnableInterfaceInterceptors in autofac using the "wrong" extension method of the ProxyGenerator - but how can I solve this?

Cheers, Manuel

like image 738
Manuel R. Wenk Avatar asked Oct 23 '25 03:10

Manuel R. Wenk


1 Answers

You can see my answer in the issue of Castle.Core.AsyncInterceptor: https://github.com/JSkimming/Castle.Core.AsyncInterceptor/issues/42#issuecomment-592074447

  1. create an adapter
public class AsyncInterceptorAdaper<TAsyncInterceptor> : AsyncDeterminationInterceptor
  where TAsyncInterceptor : IAsyncInterceptor
{
    public AsyncInterceptorAdaper(TAsyncInterceptor asyncInterceptor)
        : base(asyncInterceptor)
    { }
}
  1. create your async interceptor
public class CallLoggerAsyncInterceptor : AsyncInterceptorBase  
{
  ....
}
  1. relate the interceptor to interface
[Intercept(typeof(AsyncInterceptorAdaper<CallLoggerAsyncInterceptor>))]
public interface ISomeType
  1. register to IoC container
//register adapter
builder.RegisterGeneric(typeof(AsyncInterceptorAdaper<>));
//register async interceptor
builder.Register(c => new CallLoggerAsyncInterceptor(Console.Out));   

I've made a code sample in https://github.com/wswind/aop-learn/blob/master/AutofacAsyncInterceptor

like image 170
ws_ Avatar answered Oct 26 '25 06:10

ws_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!