【问题标题】:Use service in class MVC with Unity Ioc使用 Unity Ioc 在 MVC 类中使用服务
【发布时间】:2016-08-17 09:24:04
【问题描述】:

我有应用程序 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];

错误:

附加信息:对象引用未设置为 对象。

我如何在课堂上使用服务。谢谢!

【问题讨论】:

  • 如果将服务注入到类构造函数中会不会发生同样的事情?
  • @JB06 当我在控制器中使用时,它可以工作并且没有任何错误。只能在课堂上使用,上面会报错

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


【解决方案1】:

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

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

请注意,您很可能不需要传递整个 HTTPContext 对象,只需传递可以避免的最小值。

【讨论】:

  • 谢谢@Andrei Dragotoniu。对不起,但我不明白你的解析器,你可以为我提供示例代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多