简体   繁体   中英

ASP.NET MVC issue resolving DbContext to a Derived class

I do have a ASP.NET Core 2.0 application with Microsoft.Extensions.DependencyInjection .

I added my Context ApplicationDbContext to the Startup.cs file:

services.AddDbContext<ApplicationDbContext>(options => 
    options.UseSqlServer(DefaultConnection));

My ApplicationDbContext inherits the DbContext class:

In a generic controller I require a DbContext class:

public GenericController(DbContext context){

However Microsoft.Extensions.DependencyInjection cannot resolve the DbContext to the ApplicationDbContext registered service.

How can I inject the required DbContext class into my service class?

I'm able to change the GenericController , but the project where GenericController lies does not have reference to the ApplicationDbContext .

I'm developing a middleware, it should require DbContext that should be specialized in other projects. So the controller is in the middleware, it does not have a reference to the specialized class.

the project where GenericController lies does not have reference to the ApplicationDbContext

This is 100% of your issue.

You either need to ensure that ApplicationDbContext is in a project that the services that use it can reference:

public GenericController(ApplicationDbContext context){

or you need to create an IApplicationDbContext that is implemented by ApplicationDbContext that can be referenced from the services that use it:

public GenericController(IApplicationDbContext context){

Injecting DbContext alone isn't going to cut it because it doesn't expose any of the tables that your application needs to use.

I solved it by Just adding a Transient from derived class to parent class below the AddContext command

services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(DefaultConnection));
services.AddTransient<DIADbContext,ApplicationDbContext>();

Another solution can be to register the DbContext with a custom factory which will return the already registered ApplicationDbContext instance from the container:

services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(DefaultConnection));
services.AddScoped<DbContext, ApplicationDbContext>(s => s.GetService<ApplicationDbContext>());

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