c# - 无法从根提供程序访问作用域 DbContext
问题描述
我收到这个错误
System.InvalidOperationException:
'无法从根提供程序解析范围服务'LC.Assets.API.ApiDbFullContext'。'
注册DbContextPool
:
services.AddDbContextPool<ApiDbFullContext>(o => o.UseSqlServer(connString));
ExtensionDbHelper
:
public class ExtensionDBHelper : DisposableBase, IExtensionDBHelper
{
public ExtensionDBHelper(IServiceProvider service)
{
IHttpContextAccessor http = service.GetRequiredService<IHttpContextAccessor>();
IHostingEnvironment env = service.GetRequiredService<IHostingEnvironment>();
IApiFullDbContext db = service.GetRequiredService<ApiDbFullContext>();
this.DB = db;
this.Helper = new ApiDbContextHelper(http, db, env);
this.Worker = new ApiDbUnitOfWork(this.Helper);
}
public IApiFullDbContext DB { get; }
public IApiDbContextHelper Helper { get; }
public ApiDbUnitOfWork Worker { get; }
}
在 IApplicationBuilderExtension 中使用 LCCors:
public static IApplicationBuilder UseLCCors(this IApplicationBuilder builder, Action<LCCorsOptions> option)
{
LCCorsOptions opt = new LCCorsOptions();
option.Invoke(opt);
IExtensionDBHelper helper = new ExtensionDBHelper(builder.ApplicationServices);
ICorsOriginHub hub = GenericExpressions.CorsOriginHub(helper.Worker.GetRepo<CorsOriginHub>().DbSet).FirstOrDefault(h => h.Active && h.Version.Equals(opt.Version));
if (hub == null)
{
throw new HubNotFoundException(opt.Version);
}
else if (hub.Outdated)
{
throw new IncludeHubOutdatedException(opt.Version);
}
foreach(ICorsOriginEntry entry in hub.Items.Where(itm => itm.Active))
{
builder.UseCors(options => options.WithOrigins(entry.Host).AllowAnyMethod().AllowAnyHeader());
}
return builder;
}
解决方案
this solved my issue:
Changing from AddDbContextPool to plain AddDbContext
Altering the code in ExtensionDBHelper to:
IApiFullDbContext db = service.CreateScope().ServiceProvider.GetRequiredService<ApiDbFullContext>();
推荐阅读
- amazon-web-services - Apache Proxy Pass:连接到 websocket 服务器被拒绝
- c++ - 面向对象基础 - 将对象的结果链接到另一个对象
- python - breezypythongui 库中的单选按钮
- c++ - 连接 QSignalMapper QT 5.15.2
- http - 带有 cloudflare 的 Heroku 子域“重定向太多”
- twitter-bootstrap - 引导网格不会并排放置
- reactjs - 使用 firebase 身份验证和电子邮件验证进行私有路由时遇到问题。如何修复这些路线?
- firebase - 如何部署依赖私有包的firebase云功能?
- javascript - 不显眼的客户端验证仅在集合中的第一个属性上触发
- spring - 如何使用 Spring boot 2.5.2 配置 500 错误页面,默认设置不起作用