![](/img/trans.png)
[英]Unity (dependency injection): How to pass in a parameter to the constructor in RegisterType
[英]How to pass a type as parameter to a constructor when using Unity dependency injection
我们使用Unity依赖注入。 我们有一个需要将类型传递给其构造函数的类。
public interface ITest
{
}
public class Test : ITest
{
public Test(Type myType)
{
}
}
在容器boosterapper中,我们注册类型:
public static IUnityContainer Start()
{
IUnityContainer container = UnityInversionOfControlContainer.RegisterContainer();
container.RegisterType<ITest, Test>();
return container;
}
我们这样解决:
object actual = container.Resolve<ITest>(new ParameterOverride("myType", typeof(string)));
这给出以下错误:
Microsoft.Practices.Unity.ResolutionFailedException:依赖关系的解析失败,类型=“ ITest”,名称=“(none)”。 发生以下异常:正在解决。 异常是:InvalidOperationException-无法构造类型String。 您必须配置容器以提供该值。
在发生异常时,容器为:
解析测试,(无)(从Belastingdienst.Omvormers.Mapper.ITest映射,(无))构造函数Test(System.Type myType)的解析参数“ myType”解析System.String,(无)---> System.InvalidOperationException :不能构造字符串类型。 您必须配置容器以提供该值。
似乎unity要通过容器解析类型,并传入类型的实例,但我确实需要Type。
有人在想吗?
答案包含在Haukinger发布的链接的代码中:
object actual =
container.Resolve<IDatarecordSerializer>(
new ParameterOverride(
"type",
new InjectionParameter(typeof(string))
)
);
实际上,Unity显式地将ParameterOverride
Type
值视为文字值,而不是应自行解析的类型。 然后,它尝试解析类型为string
的实例,但失败了。
ParameterOverride
将值存储在InjectionParameterValue
实例中,然后实例将Type
解释为与其他类型不同的Type
。
参见InjectionParameterValue.cs中的第77ff行
我会尝试用Unity创建一个问题,但是我想它更多的是功能而不是错误。
同时,通过将依赖项的类型更改为以下内容,从Unity中隐藏Type
:
class HiddenType
{
public Type Type
{
get;
}
public HiddenType( Type type )
{
Type = type;
}
}
更简单的方法是注册工厂:
给出:
internal interface ITyped
{
Type Type { get; }
}
internal class Typed : ITyped
{
public Typed(Type type)
{
Type = type;
}
public Type Type { get; }
}
数量:
internal class TypedFactory : ITypedFactory
{
public ITyped Create(Type type)
{
return new Typed(type);
}
}
internal interface ITypedFactory
{
ITyped Create(Type type);
}
container.RegisterType<ITypedFactory, TypedFactory>();
Assert.AreEqual(
container.Resolve<ITypedFactory>().Create(typeof(string)).Type,
typeof(string));
不是火箭科学,而是简单,明显且易于调试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.