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'.
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.