ASP Net Core 依赖注入 - 处置

发布于 2025-01-14 03:24:10 字数 1203 浏览 3 评论 0原文

根据 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

西瑶 2025-01-21 03:24:10

这个资源也是由容器释放的吗?

容器仅处理向提供者注册并使用提供者创建的实例。在本例中,HttpResponseMessageHttpClient 创建,应由您的代码进行处置。

is this resource also disposed by the container?

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 by HttpClient, and should be disposed by your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文