【发布时间】:2020-07-15 22:23:37
【问题描述】:
我有以下派生的 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();
}
在 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"));
...
}
但我收到以下错误:
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.
如何让 DbContext 解析OnConfiguring() 中的令牌服务?
更新:需要明确的是,我不能使用构造函数注入,因为 AddDbContextPool() 要求我派生的 DbContext 有一个只有一个参数 (DbContextOptions) 的构造函数
【问题讨论】:
-
你解决了吗?
标签: c# asp.net-core .net-core entity-framework-core