我有一個ASP.NET MVC應用程序,並在我的Application_Start事件我有以下代碼:依賴注入處理case當HttpContext.Current不存在
container.RegisterType<ISessionFactory>(new ContainerControlledLifetimeManager(), new InjectionFactory(c => {
return BuildSessionFactory();
}));
container.RegisterType<ISession>(new PerRequestLifetimeManager<ISession>(), new InjectionFactory(c => {
return c.Resolve<ISessionFactory>().OpenSession();
}));
會話工廠(ISessionFactory)對於生活應用程序的長度。會話(ISession)依賴於ASP.NET請求的長度。我也將會話置於Application_EndRequest事件中。這允許我在整個應用程序中注入ISession,並按預期工作。
我現在正在嘗試將任務計劃編制到我的應用程序中。我已將以下代碼添加到Application_Start事件中:
var timer = new System.Timers.Timer(5000);
timer.Elapsed += (sender, e) => {
var thread = new Thread(new ThreadStart(() => {
var service = DependencyResolver.Current.GetService<ISomeService>();
...
}));
thread.Start();
};
timer.Enabled = true;
這應該每5秒運行一次。 ISomeService的實現在構造函數中注入了ISession,我不想改變這個類。我的問題出現時,它試圖解決ISession,因爲它試圖解決它在一個線程中HttpContext.Current爲空,因此引發異常。我想知道如何註冊會話來處理這種情況。我會很感激幫助。
感謝
這裏是我的PerRequestLifetimeManager類櫃面它可以幫助:
public class PerRequestLifetimeManager<T> : LifetimeManager {
public override object GetValue() {
return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
}
public override void RemoveValue() {
HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
}
public override void SetValue(object newValue) {
HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;
}
}
謝謝你的回答。然而,這將需要我改變我的服務(在給出的例子中是ISomeService),我不能這樣做,因爲這需要大量的重構,並且當我希望爲每個請求緩存會話時也不起作用。 – nfplee
更新:這實際上是一種享受。我從PerThreadLifetimeManager繼承了我的PerRequestLifetimeManager,並在HttpContext.Current返回null時調用基本方法。這樣它自動工作。謝謝你的幫助。 – nfplee