Lightinject with Web API - 如何获取 HttpRequestMessage?

Lightinject with Web API - How can I get the HttpRequestMessage?

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

var msg = container.GetCurrentHttpRequestMessage() 

但我在 Lightinject 中找不到匹配的。

如果您看一下 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

简单注入器 documentation 建议将此调用隐藏在自定义抽象之后,例如简单 IRequestMessageProvider。实现当然很容易创建:

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

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

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

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