简体   繁体   English

如何在控制器中每个请求只能识别我的DbContext的一个内容?

[英]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.

相关问题 如何使用来自不同程序集的 DbContext 进行迁移? - How can I use a DbContext from a different assembly for my migrations? 如何在模型中重写DBContext.SaveChanges() - How can I override DBContext.SaveChanges() in my Model 每个Web请求一个DbContext ...为什么? - One DbContext per web request… why? 我如何只能运行浏览器一次 - How can I run my browser only one time 如果每个请求使用一个DbContext实例,我也应该在每个请求上放置上下文: - If using one DbContext instance per request, should I dispose the context on each request as well: 如何获得每个类注入的 DbContext 的新实例? - How can I get a new instance of a DbContext injected per class? 如何将ASP .NET Identity / Identity Framework DbContext类合并到另一个Assembly /项目上的DbContext类 - How can I merge ASP .NET Identity/ Identity Framework DbContext class to my DbContext class which is on another Assembly/ Project 如果使用EfCore.BulkExtensions,如何为我的DbContext创建接口 - How can I create an Interface for my DbContext if I use EfCore.BulkExtensions 我可以使用 AutFac 工厂来创建我的 DbContext - Can I use an AutFac factory to create my DbContext 如何使用dbContext WPF c#在数据库sqlite中添加图像? - How can I add an image in my database sqlite using dbContext WPF c#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM