Jak*_*rth 22 c# entity-framework-core asp.net-core
在ASP.NET Core/EntityFramework Core中,services.AddDbContext <>方法将指定的上下文添加为作用域服务.我的理解是,这是Microsoft建议的dbcontext生命周期管理.
然而,我们的工程师部门对此有很多争论,许多人认为需要尽快处理上下文.那么,将dbcontext配置为Transient仍然保持通常使用的相同Repository模式(即将上下文直接注入存储库的构造函数)以及支持灵活的单元测试的最佳方法是什么?
juu*_*nas 47
生命周期是一个参数AddDbContext<>().见例子:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")),
ServiceLifetime.Transient);
Run Code Online (Sandbox Code Playgroud)
这将把它添加到具有瞬态生命周期的服务集合中.
小智 10
在我看来,将 a 注册DbContext为瞬态依赖项的一个很好的用例是在注册为单例的工作服务中。您不能在单例依赖项中使用作用域依赖项。因此,您唯一的选择是将 DbContext 注册为单例或瞬态。需要记住的是,注入的 DbContextOptions 类生命周期也需要更新。您可以通过指定服务生命周期来执行这两项操作,如下所示。
services.AddDbContext<DataContext>(options =>
{
options.UseMySQL(configurationRoot.GetConnectionString("DefaultConnection"));
options.UseLazyLoadingProxies();
}, ServiceLifetime.Transient, ServiceLifetime.Transient);
Run Code Online (Sandbox Code Playgroud)
第三个参数是 DbContextOptions 实例的服务生命周期。
| 归档时间: |
|
| 查看次数: |
12433 次 |
| 最近记录: |