.NET Core 2.0中Hangfire服务依赖Scoped DbContext的DI报错问题
.NET Core 2.0中Hangfire与Scoped DbContext的DI冲突求助
刚把项目从.NET Core 1.1升级到2.0,就遇到了个头疼的问题——之前好好的代码现在报错了:
Cannot consume scoped service 'ArithmosDaily.Data.ArithmosContext' from singleton 'ArithmosDaily.IHangfireJobSchedulerService'.
我的场景是用Hangfire做定时任务,需要通过依赖注入DbContext来从API拉数据更新数据库。DbContext是默认的Scoped实例,而Hangfire的调度服务我之前注册成了Singleton——在1.1版本里框架没检查这种Scoped被Singleton消费的情况,所以一直运行正常。
后来我试着把IHangfireJobSchedulerService改成Scoped注册,结果又出现新错误:
Cannot resolve scoped service 'ArithmosDaily.IHangfireJobSchedulerService' from root provider.
我还尝试过用services.BuildServiceProvider(false);关闭范围验证,但完全没效果。下面是我Startup类里的ConfigureServices和Configure方法代码,有没有大佬能指点一下?
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>(); }
内容的提问来源于stack exchange,提问作者Robert Burke
相关产品推荐
相关产品推荐

