The accepted answer didn't work for me as well, I ended up doing a very similar approach to the original answer, thanks @Christian for your guidance.
I wanted to inject a service into the DbContext which is responsible to load connection string dynamically based on some HTTP request header below is the code used
In Startup:
services.AddScoped<IConnectionService, ConnectionService>();
services.AddDbContext<MyDbContext>(); //Connection string will be set on event OnConfiguring
In MyDbContext:
public class MyDbContext : DbContext
{
private readonly IConnectionService _connectionService;
public MyDbContext(DbContextOptions<MyDbContext> options, IConnectionService connectionService) : base(options)
{
_connectionService = connectionService;
}
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionString = _companyConnectionService.ConnectionString; //Custom logic to read from http request header certain value and switch connection string
optionsBuilder.UseSqlServer(connectionString);
}
}
Hope this will help.