如何解决似乎没有处置使用依赖注入的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();
}
结果:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。