Unity容器解析无参数构造函数

Unity container resolve constructor with no parameter

我的一个 class 有 2 个构造函数:

public class Foo
{
    public Foo() { }

    public Foo(string bar) { }
}

当我从统一解决这个问题时,我得到一个异常,因为它寻找 string bar 参数。但我希望统一使用不带参数的构造函数实例化此 class 。我怎样才能做到这一点?

我正在使用 LoadConfiguration 方法从配置文件中注册类型。

Unity 容器配置:

container.LoadConfiguration("containerName");

配置文件:

<unity xmlns="">
  <typeAliases>
    <typeAlias alias="string" type="System.String, mscorlib" />
    <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
  </typeAliases>
  <containers>
    <container name="containerName">
      <types>
        <type type="IFoo, Assembly"
              mapTo="Foo, Assembly" />
        ...
      </types>
    </container>
  </containers>
</unity>
    构造函数上的
  • [InjectionConstructor] 属性指定在解析服务时应使用哪个构造函数

    public class Foo  : IFoo
    {
       [InjectionConstructor]
       public Foo() { }
    
       public Foo(string bar) { }
    }
    

这种方法让你 class 耦合到 Unity,你的 class 变得不那么可重用 (假设你需要在不同的场景中使用 Foo使用另一个构造函数) 并且不推荐这种方式,阅读更多关于 this here

  • 更好的方法是使用 API 并按如下方式注册 class

    container.RegisterType<IFoo>(new Foo());  
    

在这里,您可以明确定义您希望如何解决依赖关系。

  • 或者你可以使用Xml配置文件,即在<register>元素

    中指定<contructor>元素

注意我们没有在<constructor>元素里面指定<params>子元素

If no <param> child elements are present, it indicates that the zero-argument constructor should be called

详细了解 Xml 架构 here