使用 ASP.NET Web Api 的 Unity 属性拦截
Unity Attribute Interception with ASP.NET Web Api
我正在尝试使用 Unity 通过属性针对我的 ApiController 方法应用调用处理程序,但调用处理程序从未被调用。
属性:
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
};
}
}
呼叫处理程序:
public class LoggingCallHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
//.....stuff
}
}
报名人数:
container.AddNewExtension<Interception>();
container.RegisterType<IMyApiController>();
container.Configure<Interception>()
.SetInterceptorFor<IMyApiController>(new InterfaceInterceptor());
依赖解析器(使用 WebActiviatorEx):
public static class UnityWebApiActivator
{
public static void Start()
{
var resolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());
GlobalConfiguration.Configuration.DependencyResolver = resolver;
}
}
Web API 系统将使用依赖解析器来解析控制器 class(例如 MyApiController
),而不是此类控制器 class 实现的接口(例如IMyApiController
)。我不知道有什么方法可以让 Web API 系统改为请求接口(而且我怀疑是否有办法做到这一点)。
一个解决方案是拦截它自己的控制器 (MyApiController
) 但因为它是一个 class,你不能使用接口拦截器 (InterfaceInterceptor
) 而你必须像这样使用虚拟方法拦截器:
container.Configure<Interception>()
.SetInterceptorFor<MyApiController>(new VirtualMethodInterceptor());
这将要求您创建要拦截的操作方法virtual
。
请注意,您仍然可以拦截通过 InterfaceInterceptor
注入到控制器(定义为接口)的其他依赖项。这是因为 Web API 系统会要求容器将它们解析为接口,而不是 classes。
我正在尝试使用 Unity 通过属性针对我的 ApiController 方法应用调用处理程序,但调用处理程序从未被调用。
属性:
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
};
}
}
呼叫处理程序:
public class LoggingCallHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
//.....stuff
}
}
报名人数:
container.AddNewExtension<Interception>();
container.RegisterType<IMyApiController>();
container.Configure<Interception>()
.SetInterceptorFor<IMyApiController>(new InterfaceInterceptor());
依赖解析器(使用 WebActiviatorEx):
public static class UnityWebApiActivator
{
public static void Start()
{
var resolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());
GlobalConfiguration.Configuration.DependencyResolver = resolver;
}
}
Web API 系统将使用依赖解析器来解析控制器 class(例如 MyApiController
),而不是此类控制器 class 实现的接口(例如IMyApiController
)。我不知道有什么方法可以让 Web API 系统改为请求接口(而且我怀疑是否有办法做到这一点)。
一个解决方案是拦截它自己的控制器 (MyApiController
) 但因为它是一个 class,你不能使用接口拦截器 (InterfaceInterceptor
) 而你必须像这样使用虚拟方法拦截器:
container.Configure<Interception>()
.SetInterceptorFor<MyApiController>(new VirtualMethodInterceptor());
这将要求您创建要拦截的操作方法virtual
。
请注意,您仍然可以拦截通过 InterfaceInterceptor
注入到控制器(定义为接口)的其他依赖项。这是因为 Web API 系统会要求容器将它们解析为接口,而不是 classes。