似乎没有处置使用依赖注入的ef-core dbcontext [英] It seems that ef-core dbcontext using Dependency Injection is not disposed

查看:63
本文介绍了似乎没有处置使用依赖注入的ef-core dbcontext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的团队正在致力于将旧系统从delphi转换为asp.net核心.并且在测试过程中,我们发现依赖注入中使用的dbcontext从未被丢弃.

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.

因此要弄清现象的原因我已经使用Visual Studio asp.net核心Web应用程序模板(天气预报)创建了解决方案,并添加了以下代码.

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.

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;
    }
    ...
}

控制台日志

***EmptyDbContext Created
EmptyService Created
EmptyService Disposed
***EmptyDbContext Created
EmptyService Created
EmptyService Disposed
***EmptyDbContext Created
EmptyService Created
EmptyService Disposed

查看结果日志EmptyService的配置符合预期,但EmptyDbContect却没有.

Looking at the result log EmptyService was disposed well as expected, but EmptyDbContect was not.

这是因为还是我滥用dbcontext的依赖项注入?

Is this intended as or am i misusing dependency injection for the dbcontext?

推荐答案

据我所知,您应该覆盖DisposeAsync方法而不是Dispose,因为EF内核在处理dbcontext时将使用DisposeAsync.

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.

请在您的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();
     
    }

结果:

这篇关于似乎没有处置使用依赖注入的ef-core dbcontext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆