我有ASP.NET Web API應用程序。該應用程序使用Unity作爲IoC容器。該應用程序也使用了Hangfire,我正在嘗試將Hangfire配置爲使用Unity。如何用統一配置hangfire?
因此,根據documentation我使用Hangfire.Unity它將Unity容器註冊爲Hangfire中的當前作業激活器。
我有這甚至配置Hangfire.Unity
後對IBackgroundJobClient
public class MyService
{
private MyDBContext _dbContext = null;
private IBackgroundJobClient _backgroundJobClient = null;
public MyService(MyDbContext dbContext, IBackgroundJobClient backgroundJobClient)
{
_dbContext = dbContext;
_backgroundJobClient = backgroundJobClient;
}
}
但是依賴一個類就不能創建的BackgroundJobClient
&通實例,所以我不得不註冊團結容器BackgroundJobClient
每個依賴。
統一登記
OWIN啓動
public class Startup
{
public void Configuration(IAppBuilder app)
{
var container = UnityConfig.GetConfiguredContainer();
Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("HangfireConnectionString");
Hangfire.GlobalConfiguration.Configuration.UseUnityActivator(container);
// if i dont call UseSqlServerStorage() above then UseHangfireDashboard() method fails with exception
//JobStorage.Current property value has not been initialized. You must set it before using Hangfire Client or Server API.
app.UseHangfireDashboard();
app.UseHangfireServer();
RecurringJob.AddOrUpdate<MyService>(x => x.Prepare(), Cron.MinuteInterval(10));
}
}
代碼正在與此類配置。不過,我有問題:
這是使用Hangfire配置Unity的正確方法嗎?
爲什麼我需要在OWIN啓動時調用Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("HangfireConnectionString")
,即使SqlServerStorage
已經在Unity容器中註冊爲JobStorage
?
如果我不在OWIN啓動時調用UseSqlServerStorage()方法,那麼我在app.UseHangfireDashboard()
方法上得到異常。
JobStorage.Current屬性值尚未初始化。在使用Hangfire客戶端或服務器API之前,您必須先設置 。