使用 Unity 依赖注入时如何将类型作为参数传递给构造函数

How to pass a type as parameter to a constructor when using Unity dependency injection

我们使用 Unity 依赖注入。我们有一个 class 需要将类型传递给它的构造函数。

public interface ITest
{
}

public class Test : ITest
{
    public Test(Type myType)
    {

    }
}

在容器 boostrapper 中我们注册我们的类型:

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: 解析依赖失败,type = "ITest", name = "(none)"。 异常发生在:解决时。 异常是:InvalidOperationException - 无法构造 String 类型。您必须配置容器以提供此值。

发生异常时,容器是:

解析测试,(none)(映射自 Belastingdienst.Omvormers.Mapper.ITest,(none)) 解析构造函数Test(System.Type myType)的参数"myType" 解析 System.String,(none) ---> System.InvalidOperationException: 无法构造String类型。您必须配置容器以提供此值。

看来unity是想通过容器来解析类型,传入类型的实例,但我确实需要类型

有人有想法吗?

事实上,Unity 明确地将 ParameterOverride 中的 Type 值视为不是字面值,而是应该自行解析的类型。然后它尝试解析类型 string 的实例,但显然失败了。

ParameterOverride 将值存储在 InjectionParameterValue 实例中,它转而解释 Type 不同于其他类型。

参见 InjectionParameterValue.cs

中的第 77ff 行

我会尝试使用 Unity 创建问题,但我想它更多的是功能而不是错误...

与此同时,通过将依赖项类型更改为如下所示,从 Unity 中隐藏 Type

class HiddenType
{
    public Type Type
    {
        get;
    }

    public HiddenType( Type type )
    {
        Type = type;
    }
}

答案包含在 Haukinger 发布的 link 中的代码中:

object actual = 
    container.Resolve<IDatarecordSerializer>(
        new ParameterOverride(
            "type", 
             new InjectionParameter(typeof(string))
        )
    );

更简单的方法是注册工厂:

给定:

internal interface ITyped
{
    Type Type { get; }
}

internal class Typed : ITyped
{
    public Typed(Type type)
    {
        Type = type;
    }

    public Type Type { get; }
}

Fty:

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));

不是火箭科学,但简单、明显且更易于调试