简体   繁体   中英

How to get dbcontext in the library without knowing the class

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)
    {
    }
}

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM