Unity不使用类的默认构造函数

Att*_*lah 19 .net c# inversion-of-control unity-container

我有这门课:

public class Repo
{
   public Repo() : this(ConfigurationManager.AppSettings["identity"],       ConfigurationManager.AppSettings["password"])

    {

    }

   public Repo(string identity,string password)
   {
       //Initialize properties.
   }

}
Run Code Online (Sandbox Code Playgroud)

我在web.config中添加了一行,以便Unity容器自动构建此类型.

但在执行我的应用程序期间,我收到此错误消息:

  "System.InvalidOperationException : the parameter identity could not be resolved when attempting to call constructor Repo(String identity, String password)  -->Microsoft.Practices.ObjectBuilder2.BuildFailedException : The current Build operation ...."
Run Code Online (Sandbox Code Playgroud)

1)为什么Unity不使用默认构造函数?

2)假设我希望Unity使用第二个构造函数(参数构造函数),如何通过配置文件将该信息传递给Unity?

Ste*_*ook 56

Unity默认选择具有最多参数的构造函数.你必须告诉Unity明确地使用另一个.

一种方法是使用[InjectionConstructor]属性,如下所示:

using Microsoft.Practices.Unity;

public class Repo
{
   [InjectionConstructor]
   public Repo() : this(ConfigurationManager.AppSettings["identity"], ConfigurationManager.AppSettings["password"])
   {

   }

   public Repo(string identity,string password)
   {
       //Initialize properties.
   }
}
Run Code Online (Sandbox Code Playgroud)

执行此操作的第二种方法是,如果您反对使用属性来混淆类/方法,则指定在使用InjectionConstructor配置容器时要使用的构造函数:

IUnityContainer container = new UnityContainer();
container.RegisterType<Repo>(new InjectionConstructor());
Run Code Online (Sandbox Code Playgroud)

文档:

Unity如何解析目标构造函数和参数

当目标类包含多个构造函数时,Unity将使用应用了InjectionConstructor属性的构造函数.如果有多个构造函数,并且没有构造函数携带InjectionConstructor属性,Unity将使用具有最多参数的构造函数.如果有多个这样的构造函数(多于一个具有相同参数数量的"最长"),Unity将引发异常.


Lad*_*nka 21

试着以这种方式注册类型:

<register type="IRepo" mapTo="Repo">
  <constructor />
</register>
Run Code Online (Sandbox Code Playgroud)

由于param元素中没有指定constructor元素,因此它应该调用默认构造函数.

您也可以在代码中进行此注册:

container.RegisterType<IRepo, Repo>(new InjectionConstructor());
Run Code Online (Sandbox Code Playgroud)