I'm trying to use Unity to apply a call handler via an attribute against my ApiController method, but the call handler is never invoked.
Attribute:
public class LogAttribute : HandlerAttribute
{
private readonly int _order;
public LogAttribute(int order)
{
_order = order;
}
public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
{
return new LoggingCallHandler
{
Order = _order
};
}
}
The call handler:
public class LoggingCallHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
//.....stuff
}
}
Registration:
container.AddNewExtension<Interception>();
container.RegisterType<IMyApiController>();
container.Configure<Interception>()
.SetInterceptorFor<IMyApiController>(new InterfaceInterceptor());
Dependency Resolver (using WebActiviatorEx):
public static class UnityWebApiActivator
{
public static void Start()
{
var resolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());
GlobalConfiguration.Configuration.DependencyResolver = resolver;
}
}
The Web API system will use the dependency resolver to resolve the controller class (eg MyApiController
), not the interface that such controller class implements (eg IMyApiController
). I don't know of a way to make the Web API system request the interface instead (and I doubt that there is a way to do that).
One solution is to intercept the controller it self ( MyApiController
) but since it is a class, you cannot use the interface interceptor ( InterfaceInterceptor
) and instead you have to use the virtual method interceptor like this:
container.Configure<Interception>()
.SetInterceptorFor<MyApiController>(new VirtualMethodInterceptor());
This will require that you make the action methods that you want to intercept virtual
.
Please note that you can still intercept other dependencies injected to your controllers (that are defined as interfaces) via InterfaceInterceptor
. This is because the Web API system will ask the container to resolve them as interfaces, not as classes.
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.