我正在尝试使用 unity 注册依赖项并将值传递给构造函数,使用下面的代码
container.RegisterType<IProviderContext, MockOrderServiceProviderContext>(new InjectionConstructor(new Pharmacy {SiteId = 2,DistrictCode = "2"}));
但是我得到了
"The type OrderService.Business.MockOrderServiceProviderContext does not have a constructor that takes the parameters (Pharmacy)."
构造函数。
public MockOrderServiceProviderContext(params object[] objects)
{
_object = objects;
}
如何为对象数组传递构造函数值?
谢谢
最佳答案
params 关键字是用于传递参数数组的语法糖。
以下方法:
public void MyMethod(params object[] args)
{
}
可以通过以下两种方式调用,结果相同:
MyMethod(new object(), new object());
MyMethod(new []{ new object(), new object());
当 Unity 查找构造函数时,它会看到一个带有 object[]
类型参数的构造函数。所以Unity提供的值一定是数组。
InjectionConstructor
还利用了 params 关键字,其中每个参数都是一个要转发给您自己的构造函数的值。如果您使用数组实例化 InjectionConstructor
,它将尝试使用数组的每个元素并将它们转发给您的类构造函数。
为了阻止这种情况,我们需要两层包装,一层用于统一为您的类提供数组,另一层用于InjectionConstructor
使用第一个数组作为第一个也是唯一的参数。
所以你应该使用以下内容:
container.RegisterType<IProviderContext, MockOrderServiceProviderContext>(
new InjectionConstructor(new []
{
new []
{
new Pharmacy { SiteId = 2, DistrictCode = "2" }
}
}));
如果你想传递额外的项目,只需将它们添加到内部数组:
container.RegisterType<IProviderContext, MockOrderServiceProviderContext>(
new InjectionConstructor(new []
{
new []
{
new Pharmacy { SiteId = 2, DistrictCode = "2" },
new Hospital { SiteId = 5, DistrictCode="2" }
}
}));
关于dependency-injection - unity InjectionConstructor 传递对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15115942/