My team is working on converting legacy system from delphi to asp.net core. And in the course of test we found that dbcontext used in dependency injection was never disposed.
So to clarify the cause of the phenomenon I have created solution using visual studio asp.net core web app template(weathercast) and added following codes.
EmptyDbContext.cs
public class EmptyDbContext : DbContext
{
public EmptyDbContext(DbContextOptions<EmptyDbContext> options) : base(options)
{
Console.WriteLine("***EmptyDbContext Created");
}
public override void Dispose()
{
base.Dispose();
Console.WriteLine("***EmptyDbContext Disposed");
}
}
EmptyService.cs
public class EmptyService : IDisposable
{
public EmptyService()
{
Console.WriteLine("EmptyService Created");
}
public void Dispose()
{
Console.WriteLine("EmptyService Disposed");
}
...
}
Startup.cs
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<EmptyDbContext>(options =>
options.UseSqlite("DataSource=:memory:"), ServiceLifetime.Transient
);
services.AddTransient<EmptyService>();
}
...
}
WeatherForcastController.cs
public class WeatherForecastController : ControllerBase
{
...
public WeatherForecastController(ILogger<WeatherForecastController> logger, EmptyDbContext edc, EmptyService es)
{
_logger = logger;
}
...
}
Console LOG
***EmptyDbContext Created
EmptyService Created
EmptyService Disposed
***EmptyDbContext Created
EmptyService Created
EmptyService Disposed
***EmptyDbContext Created
EmptyService Created
EmptyService Disposed
Looking at the result log EmptyService was disposed well as expected, but EmptyDbContect was not.
Is this intended as or am i misusing dependency injection for the dbcontext?
