【问题标题】:It seems that ef-core dbcontext using Dependency Injection is not disposed似乎没有处理使用依赖注入的 ef-core dbcontext
【发布时间】:2020-12-02 18:54:58
【问题描述】:

我的团队正在将遗留系统从 delphi 转换为 asp.net 核心。 并且在测试过程中我们发现依赖注入中使用的dbcontext从未被释放。

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

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

控制台日志

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

查看结果日志 EmptyService 已按预期妥善处理,但 EmptyDbContect 没有。

这是打算还是我滥用 dbcontext 的依赖注入?

【问题讨论】:

    标签: asp.net-core dependency-injection entity-framework-core


    【解决方案1】:

    据我所知,您应该重写 DisposeAsync 方法而不是 Dispose,因为 EF 核心在处理 dbcontext 时将使用 DisposeAsync。

    请将以下代码添加到您的 dbcontext 中,然后您会发现它运行良好。

        public override ValueTask DisposeAsync() {
            Console.WriteLine("***EmptyDbContext Disposed");
    
            base.DisposeAsync();
    
            return new ValueTask();
         
        }
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 2018-06-19
      • 2021-12-10
      • 2019-05-07
      • 2018-05-06
      • 2021-01-21
      • 1970-01-01
      相关资源
      最近更新 更多