2016-08-17 35 views
0

我有應用程序MVC使用Unity Ioc。在Unity MVC中使用服務Ioc

聲明並初始化服務:

public static void Initialize() 
{ 
    IUnityContainer container = BuildUnityContainer(); 
    DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 
} 
private static IUnityContainer BuildUnityContainer() 
{ 
    IUnityContainer container = new UnityContainer(); 
    container.RegisterType<ImyService, myService>(new HttpContextLifetimeManager<ImyService>());; 
    return container; 
} 

在課堂上,我使用波紋管代碼:

var service = DependencyResolver.Current.GetService<ImyService>(); 

這是文件UnityControllerFactory.cs

public override object GetValue() 
{ 
    var assemblyQualifiedName = typeof(T).AssemblyQualifiedName; 
    if (assemblyQualifiedName != null) 
     return HttpContext.Current.Items[assemblyQualifiedName]; 
    return null; 
} 

當我運行的應用程序,它返回錯誤:HttpContex t.Current.Items [assemblyQualifiedName];

錯誤:

Additional information: Object reference not set to an instance of an object.

如何,我可以在我的課使用的服務。謝謝!

+0

如果將服務注入到類構造函數中,是否會發生同樣的情況? – JB06

+0

@ JB06當我在控制器中使用,它的工作,並沒有任何錯誤。只有在課堂上使用,它將錯誤以上 –

回答

0

這裏的問題是,當從類(或類庫)使用HTTPContext時,就像你正在嘗試做的那樣。這是因爲沒有任何要求。當你在控制器中使用它時,一切都會正常工作,因爲控制器是作爲請求的一部分被擊中的,所以你在那裏是黃金。

您可以更新UnityController Factory類並將所需的HTTPContext數據作爲參數傳遞,然後在需要時使用它。儘管它使事情變得複雜一點。

請注意,您很可能不需要傳遞整個HTTPContext對象,只需傳遞最小值即可。

+0

謝謝@Andrei Dragotoniu。對不起,但我不明白你的解析器,你可以爲我提供示例代碼。 –