Home > Software engineering >  How to get dbcontext in the library without knowing the class
How to get dbcontext in the library without knowing the class

Time:08-15

I am connecting dbcontext as usual

services.AddDbContext<EntityContext>()

In the library I need to get this context, but I do not know the class through which DbContext is implemented

This one doesn't work:

public class SomeService
{
    public SomeService(DbContext context)
    {
    }
}

CodePudding user response:

You need to use some of the AddDbContext overloads which allow you to specify both base service and implementation service types. The method registers both types (when they are different) in the DI container, thus allowing resolving both of them in dependent services or GetService calls.

In this particular case, you need to replace "as usual"

services.AddDbContext<EntityContext>()

with

services.AddDbContext<DbContext, EntityContext>();

Now injecting the DbContext in SomeService constructor should work (and actually receive EntityContext instance).

  • Related