我正在使用 web api 实现策略注入,对于 DI,我们使用自定义 DependancyResolver。我已经使用 InterfaceIntercept 方法来实现策略注入。它在类(自定义创建的类)的情况下工作正常,但在 ApiController 的情况下不会触发策略注入。
为了使用 APIController 调用策略注入,我创建了一个接口并用控制器实现了它。在下面共享代码:我还需要使用 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。
任何人都可以对此提出建议吗?