C#C
C#4y ago
camel

Inject AppDbContext with parameterized constructor

I'm trying to encapsulate the AppDbContext, so everything needed is passed in the constructor.

public class AppDbContext : DbContext, IAppDbContext
{
    private readonly string _connectionString;
    public DbSet<Schedule> Schedules { get; set; } // only expose DbSet for aggregate roots

    public AppDbContext(string connectionString)
    {
        _connectionString = connectionString;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(_connectionString).UseLazyLoadingProxies();
    }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
    }
}


If I omit the "<IAppDbContext, AppDbContext>", it works for projects that have a reference to the Infrastructure, where AppDbContext resides. But if I want to use the IAppDbContext to inject it anywhere, it doesn't want to migrate.

builder.Services.AddScoped<IAppDbContext, AppDbContext>(_ => new AppDbContext(builder.Configuration.GetConnectionString("MsSqlConnection")));


The error:
"Unable to create an object of type 'AppDbContext'. "
Was this page helpful?