c# - 如何配置统一容器以提供字符串构造函数值?

标签 c# visual-studio-2010 dependency-injection inversion-of-control unity-container

这是我的爸爸类(class)

 public class Dad
    {
        public string Name
        {
            get;set;
        }
        public Dad(string name)
        {
            Name = name;
        }
    }

这是我的测试方法

public void TestDad()
        {
           UnityContainer DadContainer= new UnityContainer();
           Dad newdad = DadContainer.Resolve<Dad>();    
           newdad.Name = "chris";    
           Assert.AreEqual(newdad.Name,"chris");                 
        }

这是我遇到的错误

"InvalidOperationException - the type String cannot be constructed.
 You must configure the container to supply this value"

如何配置我的 DadContainer 以使此断言通过? 谢谢

最佳答案

你应该提供一个无参数的构造函数:

public class Dad
{
    public string Name { get; set; }

    public Dad()
    {
    }

    public Dad(string name)
    {
        Name = name;
    }
}

如果你不能提供一个无参数的构造函数,你需要配置容器来提供它,或者直接在容器中注册:

UnityContainer DadContainer = new UnityContainer();
DadContainer.RegisterType<Dad>(
    new InjectionConstructor("chris"));

或通过 app/web.config 文件:

<configSections>
  <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>

<unity>
  <containers>
    <container>
      <register type="System.String, MyProject">
        <constructor>
          <param name="name" value="chris" />
        </constructor>
      </register >
    </container>
  </containers>
</unity>

关于c# - 如何配置统一容器以提供字符串构造函数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17391122/

相关文章:

c# - 删除对日志代码的依赖

c# - Unity-OnTriggerEnter 未注册碰撞

c# - 将 Azure 设置为不预编译源代码

c++ - Visual Studio 2010 + CUDA 4 : Unrecognized token error when attempting to allocate memory using NPP

visual-studio - 如何判断我是否安装了 Visual Studio 2010 Service Pack 1?

c# - 使用 Simple Injector 和 IHttpControllerActivator 解决 ASP.NET Web API 中的依赖关系

c# - ShSetFolderPath适用于win7,不适用于XP

c# - mvvm混淆模型和业务层连接

c++ - 基本 OpenCV Hello World 的错误

c# - 2层DI容器