[英]Cannot resolve scoped service DbContextOptions
我現在一直在尋找關於這個問題的明確答案,包括 github,但仍然看不到我在這里遺漏了什么:
無法從根提供程序解析范圍服務“ Microsoft.EntityFrameworkCore.DbContextOptions`1[PureGateway.Data.GatewayContext] ”。
在 Startup.cs 中:
public void ConfigureServices(IServiceCollection services)
{
//other code omitted for brevity
var connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<GatewayContext>(options => options.UseSqlServer(connection));
services.AddDbContextPool<GatewayContext>(options => options.UseSqlServer(connection));
services.AddScoped<IGatewayRepository, GatewayRepository>();
}
用法:
public sealed class MatchBrokerRouteMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<MatchBrokerRouteMiddleware> _logger;
public MatchBrokerRouteMiddleware(
RequestDelegate next,
ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<MatchBrokerRouteMiddleware>();
}
public async Task Invoke(HttpContext context, GatewayContext gatewayContext)
{
await _next(context);
}
我正在使用 netcore 2.2。
您需要使用AddDbContext
或AddDbContextPool
,而不是兩者。
DbContextPool 需要單個公共構造函數。 在下面檢查我的示例:
public partial class MyDbContext : DbContext
{
private readonly IUserResolverService _userResolverService;
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
_userResolverService = this.GetService<IUserResolverService>();
}
}
我有同樣的錯誤,但發現問題與 DbContextOptions 對象的服務生命周期有關。 默認情況下,它是“Scoped”(即為每個請求創建的),而工廠期望它是單例的。
根據這個 SO answer ,修復方法是顯式設置選項生命周期:
services.AddDbContext<GatewayContext>(options => ApplyOurOptions(options, connectionString),
contextLifetime: ServiceLifetime.Scoped,
optionsLifetime: ServiceLifetime.Singleton);
如果你真的需要它,那么你可以,這個想法是再次注冊為最后一行 DB 選項,因為 AddPooledDbContextFactory 清理它。 並且不要忘記在您的 DbContext 中只保留 1 個構造函數(僅此:public MyDbContext(DbContextOptions options) : base(options)):
DbContextOptionsBuilder MsSQL(DbContextOptionsBuilder builder) =>
builder.UseSqlServer(settings.ConnectionString, x => x.UseNetTopologySuite());
services
.AddPooledDbContextFactory<MyDbContext>(options => MsSQL(options))
.AddDbContext<MyDbContext>(options => MsSQL(options))
.AddScoped<IMyDbContext>(provider => provider.GetService<MyDbContext>())
.AddSingleton(factory => MsSQL(new DbContextOptionsBuilder()).Options);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.