[英]How can i inejct only one intance of my DbContext per request in my controllers?
My controller needs two types of service and both need to have the same interface of dbcontext, 我的控制器需要两种类型的服务,并且都需要具有相同的dbcontext接口,
public class MyController : Controller
{
protected readonly ISomeService _some;
protected reaonly IUnitOfWork _unitOfWork
public MyController(IUnitOfWork unitOfWork, ISomeService some)
{
_some = some;
_unitOfWork = unitOfWork
}
//This is my configuration //这是我的配置
services.AddDbContext<MyContext>(x =>
{
x.UseSqlServer(Configuration.GetConnectionString("coon"));
});
From the documentation : 从文档 :
Entity Framework contexts
实体框架上下文
Entity Framework contexts should be added to the service container using the scoped lifetime.
应使用范围生存期将实体框架上下文添加到服务容器中。 This is handled automatically with a call to the AddDbContext method when registering the database context.
注册数据库上下文时,通过调用AddDbContext方法自动处理。 Services that use the database context should also use the scoped lifetime.
使用数据库上下文的服务也应使用作用域生存期。
So AddDbContext would add it as a scoped life time. 因此AddDbContext会将其添加为作用域生命周期。
You need to make sure that the controllers / or other places where this is used, are also added in DI as the Scoped items. 您需要确保控制器/或其他使用它的地方也作为Scoped项目添加到DI中。
Scoped lifetime services are created once per request. 每个请求创建一次范围生命周期服务。
我发现Issuse我的问题是我使用AsyncSaveChanges insted SaveChanges,但我的服务得到了相同的instace谢谢大家:)!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.