我正在使用web api实施策略注入,对于DI我们正在使用自定义DependancyResolver。我已经使用InterfaceIntercept方法来实施策略注入。它在类(自定义创建的类)的情况下工作正常,但在ApiController情况下不会触发策略注入。策略注入拦截对WebAPI控制器不起作用
要使用APIController调用Policy Injection,我创建了一个接口&,该接口使用控制器实现。以下共享代码: 此外,我也需要与MessageHandlers调用策略。
政策注射代码:
public class LogExceptionsCallHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input,
GetNextHandlerDelegate getNext)
{
IApplicationLogger logger = new ApplicationLogger();
logger.Log(LoggingLevel.TRACE, "Entering " + input.MethodBase.DeclaringType.FullName + "." + input.MethodBase.Name);
//// Perform the operation
var methodReturn = getNext().Invoke(input, getNext);
//// Method failed, go ahead
if (methodReturn.Exception != null)
return methodReturn;
//// If the result is negative, then throw an exception
logger.Log(LoggingLevel.TRACE, "Ending " + input.MethodBase.DeclaringType.FullName + "." + input.MethodBase.Name);
return methodReturn;
}
public int Order { get; set; }
}
属性代码
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method)]
public class LogExceptionsAttribute : HandlerAttribute
{
public LogExceptionsAttribute()
{
}
public HandleLogging HandleLogging { get; set; }
public int RetryCount { get; set; }
public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
{
return new LogExceptionsCallHandler();
}
}
接口码:这个接口正在由ApiController实现
[LogExceptions]
public interface IRequestExecutionController : IHttpController
{
[LogExceptions]
HttpResponseMessage ExecuteRequest();
}
IRequestExecutionController接口由RequestExecutionController实现。 注册类型与统一:
container.RegisterType<IDDNPublicAPI.PassThrough.IRequestExecutionController, RequestExecutionController>("requestexecution");
注册拦截
container.Configure<Interception>().SetInterceptorFor<IDDNPublicAPI.PassThrough.IRequestExecutionController>(new InterfaceInterceptor());
因为我们有统一解决依赖关系的,所以我们创建了一个控制器工厂类来处理控制器创建实例。
public class UnityControllerFactory : IHttpControllerActivator
{
private IUnityContainer container;
private readonly IControllerFactory innerFactory;
public UnityControllerFactory(IUnityContainer container)
: this(container, new DefaultControllerFactory())
{ }
public UnityControllerFactory(IUnityContainer container, IControllerFactory innerFactory)
{`enter code here`
this.container = container;
this.innerFactory = innerFactory;
}enter code here
public IHttpController Create(HttpRequestMessa`enter code here`ge request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
var controller = (IHttpController)this.container.Resolve(controllerType, controllerDescriptor.ControllerName.ToLower());
return controller;
}
}
而且我们已经在全局配置文件中注册了这个控制器工厂。同样的过程为其他类工作,但不为apicontroller工作。
任何人都可以提出这方面的建议吗?