-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Closed
Milestone
Description
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>();
}
}tohidazizi and hasan-hasanov
Metadata
Metadata
Assignees
Labels
No labels