且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

依赖注入中的ASP.NET Web API处理程序和过滤器

更新时间:2023-02-20 18:15:28

由于 MessageHandlers 收藏是全球性的,它有效地单身的列表。这是罚款时,处理程序本身没有状态,没有依赖性,但在是基于坚实的设计原理的系统,它很可能是这些处理器将拥有自己的和很可能的相关性,其中有些依赖的需要寿命比单身更短。

Since the MessageHandlers collection is global, it's effectively a list of singletons. This is fine when the handler itself has no state and no dependencies, but in a system that is based on the SOLID design principles, it's very likely that those handlers will have dependencies of their own and its very likely that some of those dependencies need a lifetime that is shorter than singleton.

如果是这样的话,这样的消息处理程序不应该被创建为单例,因为在一般情况下,一个组件不应该有一生的时间长于其依赖的生存期。

If that's the case, such message handler should not be created as singleton, since in general, a component should never have a lifetime that is longer than the lifetime of its dependencies.

网页API但是缺乏一个允许对每个请求解决此类处理器的挂钩,但这种机制很容易​​通过使用代理类创建的:

Web API however lacks any hooks that allow to resolve such handler on each request, but such mechanism is easily created by using a proxy class:

public class DelegatingHandlerProxy<TDelegatingHandler> : DelegatingHandler
    where TDelegatingHandler : DelegatingHandler
{
    private readonly WindsorContainer container;

    public DelegatingHandlerProxy(WindsorContainer container)
    {
        this.container = container;
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // trigger the creation of the scope.
        request.GetDependencyScope();

        var handler = this.container.Resolve<TDelegatingHandler>();

        handler.InnerHandler = this.InnerHandler;

        var invoker = new HttpMessageInvoker(handler);

        var response = await invoker.SendAsync(request, cancellationToken);

        container.Release(handler);

        return response;
    }
}

此代理可以使用如下:

GlobalConfiguration.Configuration.MessageHandlers.Add(
    new DelegatingHandlerProxy<MyCustomHandler>(myContainer));

代理是一个单身,但它会解析指定的 MyCustomHandler 上的每个请求。