I have the following derived DbContext:
public class PowerDbContext : DbContext
{
readonly IDbAuthTokenService _authTokenService;
readonly string _connectionString;
readonly bool _useManagedIdentity;
public MyDbContext(DbContextOptions<NyDbContext> options) : base(options)
{
_authTokenService = this.GetService<IOptionsSnapshot<AzureSqlAuthTokenService>>().Value;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connection = new SqlConnection(_connectionString);
connection.AccessToken = _authTokenService.GetTokenAsync().GetAwaiter().GetResult();
}
in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddTransient<IDbAuthTokenService, AzureSqlAuthTokenService>();
services.AddEntityFrameworkSqlServer();
services.AddEntityFrameworkProxies();
services.AddDbContextPool<MyDbContext>((serviceProvider, optionsBuilder) =>
{
optionsBuilder.UseLazyLoadingProxies();
optionsBuilder.UseSqlServer(connectionString);
optionsBuilder.UseInternalServiceProvider(serviceProvider);
}, Configuration.GetAppSetting<int>("PoolSize"));
...
}
But I get the following error:
System.InvalidOperationException : Unable to resolve service for type 'Microsoft.Extensions.Options.IOptionsSnapshot<Myproject.Database.Services.AzureSqlAuthTokenService>'. This is often because no database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
How do I get the DbContext to resolve the token service in OnConfiguring()?
UPDATE: To be clear, I can't use constructor injection, since AddDbContextPool() requires my derived DbContext to have a constructor with only one parameter (DbContextOptions)