How can i inejct only one intance of my DbContext per request in my controllers?

asp.net-core c# dbcontext dependency-injection entity-framework-core

Question

My controller needs two types of service and both need to have the same interface of 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"));

  });
1
1
1/23/2019 4:05:53 PM

Popular Answer

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. Services that use the database context should also use the scoped lifetime.

So AddDbContext would add it as a scoped life time.

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 lifetime services are created once per request.

3
1/23/2019 2:45:47 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow