使用 .NET 应用程序的 Clean Architecture 模板,在设置 DbContext 时,它会默认添加范围服务。那么为什么需要为范围添加额外的一行呢?这是否提供了额外的功能?
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IApplicationDbContext>(provider =>
provider.GetService<ApplicationDbContext>());
}
最佳答案
第二行在依赖注入(inject)容器上注册接口(interface)。它增加了注入(inject)接口(interface)而不是具体实现的可能性。
使用 AddScoped 的原因是 AddDbContext 还使用请求范围实例。使用请求作用域实例而不是单例的原因是 DbContext 不是线程安全的,因此不应跨线程重复使用同一个实例。
关于c# - 如果默认添加 DbContext 范围,为什么还要添加它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69383992/