使用Web API的Lightinject - 如何获取HttpRequestMessage?

时间:2015-04-28 11:04:44

标签: ioc-container light-inject

将Lightinject与Web API一起使用时,如何获取当前的HttpRequestMessage? 例如,在Simple Injector中,我在容器上有以下扩展方法:

var msg = container.GetCurrentHttpRequestMessage() 

但是我无法在Lightinject中找到匹配的那个。

1 个答案:

答案 0 :(得分:1)

如果您查看Simple Injector Web API integration source code,您会发现实施实际上非常简单。您可以自己轻松实现。

您需要创建一个自定义DelegatingHandler,以便以后可以检索它的方式存储当前HttpRequestMessage,如下所示:

public sealed class HttpRequestMessageDelegatingHandler : DelegatingHandler {
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
        CancellationToken cancellationToken) {
        CurrentMessage = request;
        return base.SendAsync(request, cancellationToken);
    }

    public static HttpRequestMessage CurrentMessage {
        get { return (HttpRequestMessage)CallContext.LogicalGetData("RequestMessage"); }
        private set { CallContext.LogicalSetData(value, "RequestMessage"); }
    }
}

// Register this handler as follows in Web API
configuration.MessageHandlers.Add(new HttpRequestMessageDelegatingHandler());

现在您可以按如下方式检索请求的当前消息:

HttpRequestMessageDelegatingHandler.CurrentMessage

Simple Injector documentation建议隐藏自定义抽象背后的调用,例如简单的IRequestMessageProvider。当然可以轻松创建实现:

private sealed class RequestMessageProvider : IRequestMessageProvider {
    public HttpRequestMessage CurrentMessage {
        get { return HttpRequestMessageDelegatingHandler.CurrentMessage; }
    }
}

您可以直接将其注册为委托,而不是创建IRequestMessageProvider抽象加实现,如下所示:

container.Register<Func<HttpRequestMessage>>(_ =>
    () => HttpRequestMessageDelegatingHandler.CurrentMessage);

我的偏好是使用接口而不是Func<T>,因为这样的接口更加明确和可读。