容器层次结构

时间:2016-04-19 16:26:20

标签: c# dependency-injection unity-container

我正在使用Unity作为容器,我想知道它是否可以帮助我解决问题。我有2个服务,Service1和Service2。它们都依赖于另一个对象,我们称之为IFoo。我希望每个服务都能获得自己的IFoo实例,但同时我不想让其他人都这样做。基本上它应该是单身但是范围。我想过使用子容器的组合来达到这个目的但是它不能像我希望的那样工作。我们的想法是,IFoo包含一些特定于Service1和Service2的连接细节以及一些其他容器解析对象。下面是一些希望使它更清晰的代码。

解析ViewController的代码只会知道parentContainer。

var parentContainer = new UnityContainer();
parentContainer.RegisterType<IParentScope, ParentScoped>(
    new ContainerControlledLifetimeManager());

var childContainer1 = parentContainer.CreateChildContainer();
childContainer1.RegisterInstance<IFoo>(new Foo("Unique to Child Container 1"), 
    new ContainerControlledLifetimeManager());
childContainer1.RegisterType<IService1, Service1>(
    new ContainerControlledLifetimeManager());

var childContainer2 = parentContainer.CreateChildContainer();
childContainer2.RegisterInstance<IFoo>(new Foo("Unique to Child Container 2"), 
    new ContainerControlledLifetimeManager());
childContainer2.RegisterType<IService2, Service2>(
    new ContainerControlledLifetimeManager());

var viewController = parentContainer.Resolve<ViewController>();


public class ViewController
{
    public ViewController(IParentScope parentScope, IService1 service1, IService2 service2)
    {
        ParentScope = parentScope;
        Service1 = service1;
        Service2 = service2;
    }

    public IParentScope ParentScope { get; set; }
    public IService1 Service1 { get; set; }
    public IService2 Service2 { get; set; }
}

1 个答案:

答案 0 :(得分:1)

感谢您的评论。我也许没有这么好解释,但我已经意识到我可以使用像这样的命名注册来使它工作。

var foo1 = new Foo("FOO 1");
        parentContainer.RegisterInstance<IFoo>("Foo1", foo1);

        var foo2 = new Foo("FOO 2");
        parentContainer.RegisterInstance<IFoo>("Foo2", foo2);

        parentContainer.RegisterType<IService1, Service1>(new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter<IFoo>("Foo1")));
        parentContainer.RegisterType<IService2, Service2>(new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter<IFoo>("Foo2")));

一个更好的选项我现在发现它使用Service1构造函数的[Dependency(“Foo1”)]属性。这允许我指定一个命名依赖项。