Skip to content

Injecting DbContext, not the actual implementation #4558

@Muchiachio

Description

@Muchiachio

Is there a way to use AddDbContext<TContext>, to inject a particular implementation of DbContext without actually forcing other layers to depend on context's implementation? Registering DbContext implementation using AddDbContext<Context>, doesn't allow using DbContext as a Service constructor parameter.

public class Statup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddEntityFramework().AddSqlServer().AddDbContext<Context>();
    }
}

public class Context : DbContext
{
    public DbSet<Item> Items { get; set; }
}

public class Service
{
    public Service(DbContext context)
    {
        // context doesn't get injected, and I don't know what type of context it will be
        // it may be Context, it may be TestingContext, DI should take care of that
        var items = context.Set<Item>().ToArray();
    }
}

I tried a lot of DI configurations and couldn't manage this to work.
I would want to wire it up by hand like this, but it doesn't work now.

public class Statup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<DbContextOptions>(provider => ...);
        services.AddTransient<DbContext, Context>();
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions