Adding connection string to DBContext (NpgSQL, Dependency Injection, .NET Core)

asp.net-core c# entity-framework-core npgsql

Question

I am trying dynamically load up a connection string and inject it in to my DbContext inherited class. I am not sure I am doing it correctly (can't get it to work anyway).

My MyDbContext looks like this:

public class MyDbContext : DbContext
{
    private readonly string _connectionString;
    public DbSet<Things> Things{ get; set; }

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


    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql(_connectionString);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ForNpgsqlUseIdentityColumns();
    }
}

My Startup, looks like this:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddEntityFrameworkNpgsql()
        .AddDbContext<MyDbContext>(s => new MyDbContext("Host=192.168.0.1; Port=4016;Database=Test;Username=test;Password=test"))
        .BuildServiceProvider();

        services.AddMvc();

        services.AddTransient<DbContext, MyDbContext>(s => new MyDbContext("Host=192.168.0.1; Port=4016;Database=Test;Username=test;Password=test"));

    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc();

        using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();
            context.Database.Migrate();
        }

    }

The code throws an exception on the line within Configure(...):

var context = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();

The exception is:

Application startup exception: System.InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate 'MyDbContext'.

1
0
1/28/2019 11:52:48 AM

Popular Answer

EF Core has two ways for initializing a DbContext - via dependency injection or without it. You're using dependency injection, so your DbContext needs to provide a constructor that accepts DbContextOptions<TContext> (see this doc link, as @ivan-stoev wrote above).

A constructor accepting a string is only used outside of dependency injection.

1
1/28/2019 3:29:19 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow