'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://docs.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, $"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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stephen Cleary |
