ASP Net Core 依赖注入 - 处置
根据 Microsoft 的文档,IOC Container
负责清理它创建的类型并在 IDisposable
接口上调用 Dispose https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines#:~:text=Disposal%20of%20services ->那么,当 IDisposable 接口在注入对象的上下文中生成时,容器是否也会在 IDisposable 接口上调用 Dispose?
例如: 在startup.cs中:
services.AddhttpClient<CustomClient>(c => {
c.BaseAddress = new Uri(Configuration["Endpoint"]);
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));});
在这种情况下,CustomClient将由IOC容器处置,开发人员不需要调用dispose。
在CustomClient中:
var request = new HttpRequestMessage(HttpMethod.Get, $"api/users/{email}");
HttpResponseMessage httpResponse = await
httpClient.SendAsync(request).ConfigureAwait(false);
HttpResponseMessage
实现了IDisposable
,我是否需要使用using HttpResponseMessage httpResponse = wait httpClient.SendAsync(request).ConfigureAwait(false);
那么 dispose 会被调用还是这个资源也被容器释放了?
According to Microsofts documentation, the IOC Container
is repsonsible for cleanup of types it creates and calls Dispose on IDisposable
Interfaces
https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines#:~:text=Disposal%20of%20services
-> so will the container also call Dispose on IDisposable
Interfaces when they are generated in the context
of an injected object?
e.g.:
in startup.cs:
services.AddhttpClient<CustomClient>(c => {
c.BaseAddress = new Uri(Configuration["Endpoint"]);
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));});
in this case, CustomClient will be disposed by the IOC Container, dispose is not needed to be called by developer.
in CustomClient:
var request = new HttpRequestMessage(HttpMethod.Get, quot;api/users/{email}");
HttpResponseMessage httpResponse = await
httpClient.SendAsync(request).ConfigureAwait(false);
HttpResponseMessage
implements IDisposable
, Do i need to use using HttpResponseMessage httpResponse = await httpClient.SendAsync(request).ConfigureAwait(false);
so dispose will be called or is this resource also disposed by the container?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
容器仅处理向提供者注册并使用提供者创建的实例。在本例中,
HttpResponseMessage
由HttpClient
创建,应由您的代码进行处置。The container only disposes instances which are registered with the provider and which the provider is used to create. In this case,
HttpResponseMessage
is created byHttpClient
, and should be disposed by your code.