ASP-Net核心依赖项注入-处置



根据微软的文档,IOC Container可用于清理它在IDisposable接口上创建和调用Dispose的类型https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines#:~:text=处置%20个服务中的%20个->那么,当IDisposable接口在注入对象的context中生成时,容器是否也会调用它们上的Dispose?

例如:在启动.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 = await httpClient.SendAsync(request).ConfigureAwait(false);吗那么dispose将被调用,还是容器也处理了这个资源?

容器是否也处理了此资源?

容器只处理已向提供程序注册并且提供程序用于创建的实例。在这种情况下,HttpResponseMessage是由HttpClient创建的,应该由您的代码处理。

最新更新