简体   繁体   English

ASP Net Core 依赖注入 - 处理

[英]ASP Net Core Dependency Injection - 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/do.net/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?根据 Microsoft 的文档, IOC Container负责清理它创建的类型,并在IDisposable接口上调用 Dispose https://learn.microsoft.com/en-us/do.net/core/extensions/dependency-injection-guidelines# :~:text=Disposal%20of%20services -> 因此,当 IDisposable 接口是在注入的 object 的context中生成时,容器还会在IDisposable接口上调用 Dispose 吗?

eg: in startup.cs:例如:在 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.在这种情况下,CustomClient 将由 IOC Container 进行处置,开发者无需调用处置。

in CustomClient:在自定义客户端中:

var request = new HttpRequestMessage(HttpMethod.Get, $"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); HttpResponseMessage实现IDisposable ,我是否需要使用using HttpResponseMessage httpResponse = await httpClient.SendAsync(request).ConfigureAwait(false); so dispose will be called or is this resource also disposed by the container?所以将调用 dispose 或者这个资源是否也被容器处理?

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.在这种情况下, HttpResponseMessageHttpClient创建,应该由您的代码处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM