I have a ASP.NET Core 6 Web API with this disposable service class:
public interface IMyService: IDisposable { }
public class MyService: IMyService
{
public void Dispose() => Console.WriteLine("Disposing..."); // never called
}
In program.cs I have this service injected as a singleton:
builder.Services.AddSingleton<IMyService, MyService>();
According to all docs that I could find, the app should call MyService.Dispose()
when it shuts down. However this doesn't happen.
What am I missing?
Steps to reproduce:
- Create a ASP.NET Core WebAPI project using default template (VS2022)
- At the end of program.cs add this code:
public interface IMyService : IDisposable { } public class MyService : IMyService { public MyService() { } public void Dispose() => Console.WriteLine("Disposing..."); // never called }
- Put a breakpoint on constructor and one on Dispose
- Add this line somewhere at the top (after builder is created):
// Add services to the container. builder.Services.AddSingleton<IMyService, MyService>();
- In WeatherForecastController.cs change the constructor signature like this:
public WeatherForecastController( ILogger<WeatherForecastController> logger, IMyService myService)
- Run the app. In the browser click Get then Try it out then Execute
- The break point in
MyService
constructor shd be hit - Close the browser. The
Dispose
breakpoint is not hit, Output message is not displayed