我有應用程序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.
如何,我可以在我的課使用的服務。謝謝!
如果將服務注入到類構造函數中,是否會發生同樣的情況? – JB06
@ JB06當我在控制器中使用,它的工作,並沒有任何錯誤。只有在課堂上使用,它將錯誤以上 –