简体   繁体   中英

Adding DI to DbContext with Base implementation asp.net core 2.0

I have a base implementation of my DbContext as follows;

public abstract class DataContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>, IDataContext
{
    public DataContext(DbContextOptions<DataContext> options)
    : base(options)
    {
    }

where my implementation is

public class MyDataContext : DataContext, IMyDataContext
{
    public MyDataContext(DbContextOptions<DataContext> options)
    : base(options)
    {

    }

Now when running Migrations I use the following (successfully);

public class MyContextFactory : IDesignTimeDbContextFactory<MyDataContext>
{
    public MyContextFactory()
    {
    }

    public MyDataContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<DataContext>();
        builder.UseSqlServer(DbGlobals.DevDatabase);

        return new MyDataContext(builder.Options);
    }
}

however when I try to set the DbContext in my WebApi Startup.cs I add as follows;

        services.AddDbContext<MyDataContext>(
            options => options.UseSqlServer(DbGlobals.DevDatabase));

However, when I run this I get the following Error;

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[MyProject.Data.DataContext]' while attempting to activate 'MyProject.Data.EF.MyDataContext'.

I think its trying to inject the DbContextOptions<MyDataContext> instead of DbContextOptions<DataContext> . How do I resolve it so it passes in the right DbContextOptions please?

Alternatively if I adjust my MyDbContext class constructor to take DbContextOptions<MyDataContext> then how can I cast this down to the base implementation?

Based on the thread I found here

EntityFrameworkCore Issues

By setting the DataContext base class to be;

public abstract class DataContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>, IDataContext
{
    public DataContext(DbContextOptions options)
    : base(options)
    {
    }

and then on MyDataContext

public class MyDataContext : DataContext, IMyDataContext
{
    public MyDataContext(DbContextOptions<DataContext> options): base(options)
    {

    }

Then the dependency injection worked.

In my case, I was using the constructor like this:

public DataContext(DbContextOptions<DbContext> options) : base(options) { } 

I just used the non-generic DbContextOptions and my problem disappeared:

public DataContext(DbContextOptions options) : base(options) { } 

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