Unity独立接口注册



一个接口依赖于相同类型的接口来完成某些操作。但当我试图用团结注册时,我得到了

"System.StackOverflowException"类型的未处理异常出现在Microsoft.Practices.Unity.DLL 中

我认为它陷入了一种自我参照的循环,充满了记忆。

我的做法有什么不对吗。我该如何解决?

我有这样的界面;

  public interface IEnvironment
{
    string RootUrl { get; set; }
    string ImagesPath { get; set; }
    IEnvironment DependentEnvironment { get; set; }
}

这是我运行的代码环境的表示,如Localhost、Production、Windows Phone Simulator等

我现在有两个类实现这一点;

class Localhost : IEnvironment
{
    public string RootUrl { get; set; }
    public string ImagesPath { get; set; }
    public IEnvironment DependentEnvironment { get; set; }
    public Localhost(IEnvironment dependentEnvironment)
    {
        ImagesPath = "images";
        DependentEnvironment = dependentEnvironment;
    }
}

public class WindowsPhoneSimulator : IEnvironment
    {
        public string RootUrl { get; set; }
        public string ImagesPath { get; set; }
        public IEnvironment DependentEnvironment { get; set; }
        public WindowsPhoneSimulator(IEnvironment dependentEnvironment)
        {
            ImagesPath = "/Assets/images";
            DependentEnvironment = dependentEnvironment;
        }
    }

所以一个环境可以依赖另一个环境?为什么?因为例如WindowsPhoneSimulator可以对localhost进行api调用,当我部署应用程序时,我会将注入更改为ProductionEnvironment。所以它应该知道该调用哪个环境。

当我开始解决我的对象时,问题就开始了,比如;

    IocContainer.RegisterType<IEnvironment, WindowsPhoneSimulator>();

有什么建议吗?

您还没有展示如何注册类型,但可能只是使用标准RegisterType方法注册它们。当你注册第二个类型时,它会覆盖第一个类型,所以Unity只知道你的一个类(第二个注册的类)。然后,为什么会出现堆栈溢出异常是有道理的,因为它正试图创建一个实例,比如WindowsPhoneSimulator类,以传递到WindowsPhoneStulator类中。。。这显然是做不到的。

相反,您需要将unity中的类型注册为"命名类型",然后当您想要使用其中一个类型时,在解析类时创建一个依赖重写,以告诉unity您想要使用哪个类型。

因此,将类型注册为命名类型:

container.RegisterType<IEnvironment, Localhost>("Localhost")
container.RegisterType<IEnvironment, WindowsPhoneSimulator>("WindowsPhoneSimulator")

然后,当你想创建类型时,可以这样做:

DependencyOverride dep = new DependencyOverride(typeof(IEnvironment)
                        , container.Resolve<IEnvironment>("Localhost"));
IEnvironment obj2 = container.Resolve<IEnvironment>("WindowsPhoneSimulator", dep);

在上面的示例中,首先解析Localhost类的实例,然后使用该实例创建dependencyOverride,并将其传递到WindowsPhoneSimulator类的构造函数中。因此,WindowsPhoneSimulator在构造时会传递Localhost的实例。

最新更新