嵌套泛型注册使用Unity配置文件

时间:2015-06-01 21:04:14

标签: .net dependency-injection unity-container

我有一个接口和实现如下:

public interface IDataProcessor<T, U>
    {
        U Process(T data);
    }

public sealed class CustomDataProc: IDataProcessor<List<string>, Dictionary<string, Dictionary<string, List<string>>>>
    {
          ...
    }

当我使用下面的传统风格注册此实现时,一切都解决得很好并且没问题。

container.RegisterType<IDataProcessor<List<string>, Dictionary<string, Dictionary<string, List<string>>>>, CustomDataProc>();

现在,当使用XML如下注册(即调用container.LoadConfiguration(section))时,但是在解析根对象时它会失败。

<typeAliases>
    <typeAlias alias ="Dictionary" type ="System.Collections.Generic.Dictionary`2, mscorlib" />
    <typeAlias alias ="List" type ="System.Collections.Generic.List`1, mscorlib" />
...
</typeAliases>
<container>
<register type="IDataProcessor[List[string], Dictionary[string, Dictionary[string, List[string]]]]" mapTo="CustomDataProc"/>
...
</container>

失败,错误

"Resolution of the dependency failed, type = ... 
while resolving.\r\nException is: InvalidOperationException - The current type, 
IDataProcessor`2[System.Collections.Generic.List`1[System.String],System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[System.String]]]], 
is an interface and cannot be constructed. Are you missing a type mapping?

我认为它与嵌套泛型有关,因为我的其他类型映射与单一泛型工作正常。

知道如何成功解决这个问题吗?

由于

1 个答案:

答案 0 :(得分:1)

这对我有用......

<typeAliases>
  <typeAlias alias="IDataProcessor" type="StackOverflow_30583255.IDataProcessor`2, StackOverflow_30583255" />
  <typeAlias alias="CustomDataProc" type="StackOverflow_30583255.CustomDataProc, StackOverflow_30583255" />
</typeAliases>
<container>
  <register type="IDataProcessor`2[List[string],Dictionary[string,Dictionary[string,List[string]]]]" mapTo="CustomDataProc" />
</container>