哦!这是一个非常奇怪的问题。我将注册这两种类型,但没有什么可以正常工作。
<unity>
<typeAliases>
<typeAlias alias="IEqualityComparer`1"
type="System.Collections.Generic.IEqualityComparer`1, mscorlib" />
<typeAlias alias="singleton"
type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
<typeAlias alias="EqualityComparer`1"
type="System.Collections.Generic.EqualityComparer`1, mscorlib" />
</typeAliases>
<containers>
<container>
<types>
<register type="IEqualityComparer`1"
mapTo="EqualityComparer`1">
<lifetime type="singleton" />
</register>
</types>
</container>
</containers>
</unity>
这是我的控制者:
public class MyController : MyExtendedController {
private readonly IEqualityComparer<int> _fakeComparer;
public ResourcesController(IEqualityComparer<int> fakeComparer) {
_fakeComparer = fakeComparer;
}
}
在解析Controller时Unity会抛出异常:
Resolution of the dependency failed, type = "MyController", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type EqualityComparer`1 cannot be constructed. You must configure the container to supply this value.
-----------------------------------------------
At the time of the exception, the container was:
Resolving MyController,(none)
Resolving parameter "fakeComparer" of constructor MyController(System.Collections.Generic.IEqualityComparer`1[[int, mscorelib]] fakeComparer)
Resolving System.Collections.Generic.EqualityComparer`1[int, mscorelib],(none) (mapped from System.Collections.Generic.IEqualityComparer`1[int, mscorelib], (none))
任何建议都将受到赞赏;)
答案 0 :(得分:2)
更新回答
原因是EqualityComparer<T>
是一个抽象类,您可以看到on MSDN。 Unity无法实例化抽象类,您必须提供具体的实现。
第一个回答
您是否配置了服务器:
var container = new UnityContainer();
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers.Default.Configure(container);