我有一個MVC應用程序,它使用Unity作爲其IoC容器,並使用PerRequestLifetimeManager
在我的應用程序中定義了多個服務。PerRequestLifetimeManager只能在HTTP請求的上下文中使用
container.RegisterType<IFileService, FileService>();
一切正常,只是當我試圖推出我的解決方案自動執行任務(如的SharePoint TimerJobs),在不同的時間間隔開始。
對於這一點,我在一個單獨的項目中定義的ServiceLocator
-Type類ContainerManager
,但這基本上是這樣的:
public static object Resolve(string typeName)
{
var type = Type.GetType(typeName);
return Resolve(type);
}
public static object Resolve(Type type)
{
object result = DependencyResolver.Current.GetService(type);
return result;
}
public static T Resolve<T>() where T : class
{
object result = DependencyResolver.Current.GetService<T>();
return (T)result;
}
public static object Resolve(string typeName)
{
var type = Type.GetType(typeName);
return Resolve(type);
}
public static object Resolve(Type type)
{
object result = DependencyResolver.Current.GetService(type);
return result;
}
public static T Resolve<T>() where T : class
{
object result = DependencyResolver.Current.GetService<T>();
return (T)result;
}
而且在我的「任務管理器」我做了以下內容:
var unitOfWork = ContainerManager.Resolve<IFileService>();
手動啓動時(當源自HttpRequest時),現在這個工作。但是,這通過我的後臺線程啓動時不起作用。
我已經試過直接(沒有我的ServiceLocator)呼籲團結,但後來我得到異常:PerRequestLifetimeManager can only be used in the context of an HTTP request
這就是我如何創建我的任務:
private ITask CreateTask()
{
ITask task = null;
if (IsEnabled)
{
var type = System.Type.GetType(Type);
if (type != null)
{
object instance = ContainerManager.Resolve(type);
if (instance == null)
{
// Not resolved
instance = ContainerManager.ResolveUnregistered(type);
}
task = instance as ITask;
}
}
return task;
}
我缺少什麼?
我試圖理解你的問題。當你說「但是,通過我的後臺線程啓動時,這不起作用」,你是什麼意思?你有例外嗎?所以,每個HTTP請求都不會執行TimerJobs,它們是按照某個時間表執行的,對嗎?你希望他們使用他們自己的'FileService'實例,對嗎? –
@YacoubMassad沒錯。當我創建一個要在我的控制器中運行的新任務(源自HTTP請求)時,Unity能夠解決依賴關係。但是,當我的後臺計時器執行它時,統一不會解析依賴關係,並在調用ServiceLocator之後返回「null」。 – SeToY
當你說任務,你的意思是[這個類](https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v = vs.110).aspx)從TPL ?我雖然你正在使用SharePoint的其他類型的任務?你能提供一些關於你如何創建任務的代碼嗎? –