【问题标题】:Unity container resolve constructor with no parameterUnity容器解析没有参数的构造函数
【发布时间】:2016-03-10 05:25:11
【问题描述】:

我的一个班级有 2 个构造函数:

public class Foo
{
    public Foo() { }

    public Foo(string bar) { }
}

当我从统一解决这个问题时,我得到一个异常,因为它会查找 string bar 参数。但是我希望统一使用没有参数的构造函数来实例化这个类。我怎样才能做到这一点?

我正在使用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>

【问题讨论】:

    标签: c# constructor .net-4.0 unity-container


    【解决方案1】:
    • [InjectionConstructor] 构造函数上的属性指定在解析服务时应使用哪个构造函数

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

    这种方法让你的类与 Unity 耦合,你的类变得不那么可重用(想象一下,你需要在需要使用另一个构造函数的不同场景中使用 Foo)推荐,阅读更多关于this here

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

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

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

    • 您也可以使用Xml 配置文件,即在&lt;register&gt; 元素内指定&lt;contructor&gt; 元素

    请注意,我们没有在 &lt;constructor&gt; 元素中指定 &lt;params&gt; 子元素

    如果不存在&lt;param&gt;子元素,则表示应该调用零参数构造函数

    查看更多关于Xml架构here

    【讨论】:

    • 谢谢,我试试最后一个。
    • @Kael 很高兴如果有帮助
    猜你喜欢
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    相关资源
    最近更新 更多