使用Unity Ioc中的MVC类服务

时间:2016-08-17 09:24:04

标签: asp.net-mvc unity-container ioc-container

我有应用程序MVC使用Unity 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;
}

当我运行应用程序时,它返回错误: HttpContext.Current.Items [assemblyQualifiedName];

错误:

  

附加信息:对象引用未设置为的实例   对象

如何在班上使用服务。谢谢!

1 个答案:

答案 0 :(得分:0)

这里的问题是,当您尝试从类(或类库)中使用HTTPContext时,它是null。那是因为没有要求合作。当你从一个控制器中使用它时一切正常,因为控制器是作为请求的一部分命中的,所以你在那里得到了金色。

您可以更新UnityController Factory类并将所需的HTTPContext数据作为参数传递,然后您可以在需要时使用它。虽然它使事情变得复杂。

注意,您很可能不需要传递整个HTTPContext对象,只需通过您可以逃脱的最小值。

相关问题