3

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?

1 Answer 1

3

As far as I know, you should override the DisposeAsync method instead of Dispose, since the EF core will use DisposeAsync when it dispose the dbcontext.

Please add below codes into your dbcontext and then you will find it works well.

    public override ValueTask DisposeAsync() {
        Console.WriteLine("***EmptyDbContext Disposed");

        base.DisposeAsync();

        return new ValueTask();
     
    }

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't you either want to return the base.DisposeAsync, or at least await it or something?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.