似乎没有处置使用依赖注入的ef-core dbcontext EmptyDbContext.cs EmptyService.cs Startup.cs WeatherForcastController.cs 控制台日志

问题描述

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

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

EmptyDbContext.cs

select dst.*
from dept_start_times dst
where dst.start_time = (select max(dst2.start_time)
                        from dept_start_times dst2
                        where dst2.department = dst.department
                       );

EmptyService.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");
    }
}

Startup.cs

public class EmptyService : IDisposable
{
    public EmptyService()
    {
        Console.WriteLine("EmptyService Created");
    }

    public void Dispose()
    {
        Console.WriteLine("EmptyService Disposed");
    }
    ...
}

WeatherForcastController.cs

public class Startup
{
    ...
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddDbContext<EmptyDbContext>(options => 
            options.UseSqlite("DataSource=:memory:"),ServiceLifetime.Transient
        );
        services.AddTransient<EmptyService>();
    }
    ...
}

控制台日志

public class WeatherForecastController : ControllerBase
{
    ...
    public WeatherForecastController(ILogger<WeatherForecastController> logger,EmptyDbContext edc,EmptyService es)
    {
        _logger = logger;
    }
    ...
}

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

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

解决方法

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

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

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

        base.DisposeAsync();

        return new ValueTask();
     
    }

结果:

enter image description here

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...