这是我的 dad
类
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
以使此断言通过?
谢谢
答案 0 :(得分:28)
您应该提供无参数构造函数:
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>