【发布时间】:2018-10-26 00:29:40
【问题描述】:
我在 2.0 中遇到了一个错误,而我过去在 .Net Core 1.1 中却没有。
Cannot consume scoped service 'ArithmosDaily.Data.ArithmosContext' from singleton 'ArithmosDaily.IHangfireJobSchedulerService'.
我正在使用 Hangfire,我需要它来访问我的数据库(所以我通过 DI 注入我的上下文)以按计划使用来自 API 的一些数据更新数据库。所以看起来 DbContext 被实例化为 Scoped,我将 Hangfire 服务设置为 Singleton。在 Core 1.1 中,没有检查嵌套在 Singleton 中的 Scoped。我知道这个概念是可行的,因为我在 Core 1.1 项目中将它从我的另一个项目中剥离出来,并将 Context 嵌套在我的 Singleton 服务中工作正常。 (这让我很恼火,微软觉得有必要控制我只是因为我可能做坏事)。
所以,我将 Hangfire 服务从 Singleton 更改为 Scoped,希望由于我的 DbContext 显然是 Scoped,因此 Scoped 内的 Scoped 会很好,但我得到了这个错误:Cannot resolve scoped service 'ArithmosDaily.IHangfireJobSchedulerService' from root provider. 我仍然不知道那是什么意思.
在进行了一些挖掘之后,我发现了帖子底部的两个链接(到目前为止,我只能找到这些链接)。我尝试按照第一个链接中的建议在我的启动中设置services.BuildServiceProvider(false);,但这并没有改变我的配置中的任何内容:设置服务时仍然出现错误。
我完全被难住了,不知道还能尝试什么。也许我在错误的地方有代码?我不确定。
这是我的启动和配置代码:
public void ConfigureServices(IServiceCollection services)
{
services.BuildServiceProvider(false);
string conn = Configuration.GetConnectionString("Arithmos");
services.AddDbContext<ArithmosContext>(options => options.UseSqlite(conn));
services.AddMvc();
services.AddHangfire(x => x.UseSQLiteStorage(conn));
services.AddScoped<IHangfireJobSchedulerService, HangfireJobSchedulerService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
{
lifetime.ApplicationStarted.Register(OnStartup);
lifetime.ApplicationStopping.Register(OnShutdown);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
app.UseExceptionHandler("/Error");
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseHangfireServer();
app.UseHangfireDashboard(options: new DashboardOptions
{
Authorization = new[] { new HangfireAuthorizationFilter() }
});
jobSchedulerService = app.ApplicationServices.GetRequiredService<IHangfireJobSchedulerService>();
}
我遇到过这些问题,但对我帮助不大:
ASP.Net Core 2 ServiceProviderOptions.ValidateScopes Property
【问题讨论】:
标签: c# dependency-injection asp.net-core-2.0