Home > Software design >  ASP Net Core Dependency Injection - dispose
ASP Net Core Dependency Injection - dispose

Time:03-17

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 of services -> 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?

CodePudding user response:

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.

  • Related