有选择地解决同一接口的依赖关系

时间:2012-02-24 03:52:37

标签: c# .net inversion-of-control unity-container

我们正在使用Unity框架进行依赖注入。我正在为同一个类注册两个具体的实现。像...

container.RegisterType<IInterface, MyFirstClass>("first");
container.RegisterType<IInterface, MySecondClass>("second");

现在有很少的类为上面的接口提供了构造注入..

 public class Class1
    {
       private IInterface _myClass
       public Class1 (IInterface myClass)
       {
         _myClass = myClass // // should be instance of MyFirstClass
       }
 //.. other code
    }

   public class Class2
    {
       private IInterface _myClass

       public Class2 (IInterface myClass)
       {
         _myClass = myClass // should be instance of MySecondClass
       }
 //.. other code
    }

所以现在我们要在上面两个类中选择性地解决IInterfaceClass1Class2

Class1应该被MyFirstClass注明,而Class2应注明MyFirstClass。这可以通过Unity框架实现吗?如果不是哪个其他IoC框架支持这个?

请提出您的意见。

1 个答案:

答案 0 :(得分:3)

试试这个

var container = new UnityContainer();
container.RegisterType<IInterface, MyFirstClass>("first");
container.RegisterType<IInterface, MySecondClass>("second");
container.RegisterType<Class1>(new InjectionConstructor(new ResolvedParameter(typeof(IInterface), "first")));
container.RegisterType<Class2>(new InjectionConstructor(new ResolvedParameter(typeof(IInterface), "second")));
var class1 = container.Resolve<Class1>();
Assert.IsInstanceOfType(class1.MyClass, typeof(MyFirstClass));
var class2 = container.Resolve<Class2>();
Assert.IsInstanceOfType(class2.MyClass, typeof(MySecondClass));

public class MyFirstClass : IInterface
{
}

public class MySecondClass : IInterface
{
}

public interface IInterface
{
}

public class Class1
{
  public IInterface MyClass { get; set; }
  public Class1(IInterface myClass)
  {
    MyClass = myClass;
  }
}
public class Class2
{
  public IInterface MyClass { get; set; }
  public Class2(IInterface myClass)
  {
    MyClass = myClass;
  }
}