gpt4 book ai didi

c# - SimpleInjector 的 WebAPIRequest 生命周期是否包括消息处理程序?

转载 作者:行者123 更新时间:2023-11-30 14:10:50 28 4
gpt4 key购买 nike

我是 SimpleInjector 的新手,正在研究将其与 WebAPI 结合使用的示例。我用了 SimpleInjector.Integration.WebApi.WebHost.QuickStart nu-get 包,然后为我的测试注册一个简单类型,如下所示:

container.RegisterWebApiRequest<SimplePOCO>();

从 ApiController 方法内部,我可以请求一个实例。到目前为止,一切都很好。我想将我的测试扩展到管道的早期,特别是消息处理程序。所以我创建了一个简单的 DelegatingHandler,例如:

protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken) {
Task<HttpResponseMessage> response;

var container = SimpleInjectorWebApiInitializer.container;
var rc = container.GetInstance<SimplePOCO>();
response = base.SendAsync(request, cancellationToken);
response.ContinueWith((responseMsg) => { });

return response;
}

调用 GetInstance<SimplePOCO>()错误并显示以下消息:

The registered delegate for type SimplePOCO threw an exception. The SimplePOCO is registered as 'Web API Request' lifestyle, but the instance is requested outside the context of a Web API Request.

我做错了什么吗?消息处理程序是否在 WebAPI 请求的生命周期之外?考虑到它们是多么完整,这似乎很奇怪。如果消息处理程序在生命周期之外,是否有更长的生命周期包含消息处理程序?

最佳答案

Are Message Handlers outside the lifetime of a WebAPI request?

嗯,事实上,他们是。除非您明确触发 IDependencyScope 的创建,否则会在 DefaultHttpControllerActivator 内部创建 IDependencyScope(通过调用 request.GetDependencyScope()) .Create 方法。

要确保您的代码在依赖范围内运行,您所要做的就是在您的处理程序中显式调用 request.GetDependencyScope():

protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken) {

// trigger the creation of the scope.
request.GetDependencyScope();

Task<HttpResponseMessage> response;

var container = SimpleInjectorWebApiInitializer.container;
var rc = container.GetInstance<SimplePOCO>();
response = base.SendAsync(request, cancellationToken);
response.ContinueWith((responseMsg) => { });

return response;
}

关于c# - SimpleInjector 的 WebAPIRequest 生命周期是否包括消息处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22311361/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com