我正在使用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工作。
任何人都可以提出這方面的建議嗎?