當我執行后臺作業并嘗試解決所有依賴項時,出現例外:
Microsoft.EntityFrameworkCore.Query[10100]
迭代背景關系型別“MyProj.DAL.ApplicationContext”的查詢結果時發生例外。
System.ObjectDisposedException:無法訪問已釋放的背景關系實體。此錯誤的一個常見原因是釋放從依賴注入中決議的背景關系實體,然后嘗試在應用程式的其他地方使用相同的背景關系實體。如果您在背景關系實體上呼叫“Dispose”或將其包裝在 using 陳述句中,則可能會發生這種情況。如果你使用依賴注入,你應該讓依賴注入容器負責處理背景關系實體。
物件名稱:'ApplicationContext'
在 Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
在 Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
我的代碼 - 在ConfigureServices(IServiceCollection services):
services.AddHangfire(cfg => cfg
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseMemoryStorage());
services.AddHangfireServer();
在Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider provider):
GlobalConfiguration.Configuration.UseActivator(new ContainerJobActivator(provider));
app.UseHangfireDashboard()
和
public class ContainerJobActivator : JobActivator
{
private IServiceProvider _container;
public ContainerJobActivator(IServiceProvider container)
{
_container = container;
}
public override object ActivateJob(Type type)
{
return _container.GetService(type);
}
}
我的資料庫背景關系
services.AddEntityFrameworkNpgsql().
AddDbContext<ApplicationContext>(opt =>
opt.UseNpgsql("server=localhost;port=5432;database=database;uid=root;password=password;"));
uj5u.com熱心網友回復:
我們需要在作業中解決 IServiceScopeFactory,而不是獲得我們的服務
using (var scope = _factoryScope.CreateScope())
{
_articleRepository = scope.ServiceProvider.GetService<IArticleRepository>() ?? throw new ArgumentNullException();
// your job here.....
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425443.html
標籤:asp.net-mvc 吊火
