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

标签 c# .net 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.
   }

}

我在 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 ...."

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

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

最佳答案

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.
   }
}

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

IUnityContainer container = new UnityContainer();
container.RegisterType<Repo>(new InjectionConstructor());

来自documentation :

How Unity Resolves Target Constructors and Parameters

When a target class contains more than one constructor, Unity will use the one that has the InjectionConstructor attribute applied. If there is more than one constructor, and none carries the InjectionConstructor attribute, Unity will use the constructor with the most parameters. If there is more than one such constructor (more than one of the "longest" with the same number of parameters), Unity will raise an exception.

关于c# - Unity不使用类的默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5253149/

相关文章:

c# - 如何在不使用 Subjects 或 .NET 事件的情况下创建在方法调用时发出的 IObservable?

c# - 在现有接口(interface)上应用 ServiceContract 和 OperationContract

java - Spring Java 对象依赖注入(inject)

testing - 实例化一个类进行测试

.net - 在 Unity 中使用泛型... InvalidCastException

c# - ServiceStack.OrmLite : Where is the method to write custom SQL and get result set back?

c# - 如何通过静态类或其他方式更改密封类方法?

c# - 如何将 PdfPTable 插入现有的 PDF 模板?

c# - C# 中的多路音频和视频

c# - 根据 Entity Framework 中的数据库列值显示枚举文本