无法解析 Unity 容器中的字典
我刚刚偶然发现了这一点:
在 Unity 容器中,我想注册 IDictionary
;假设它是 IDictionary
_unityContainer = new UnityContainer()
.RegisterType<IDictionary<string, int>, Dictionary<string, int>>();
但如果我尝试
var d = _unityContainer.Resolve<IDictionary<string, int>>();
它无法解析...
我得到...
Microsoft.Practices.Unity.ResolutionFailedException: Microsoft.Practices.Unity.ResolutionFailedException: 解析依赖项失败,类型=“System.Collections.Generic.IDictionary`2[System.String,System.Int32]”,名称=“(无)”。 while:解决时发生异常。
例外是: InvalidOperationException - 类型 Dictionary`2 有多个长度为 2 的构造函数。无法消除歧义。
发生异常时,容器为:
Resolving System.Collections.Generic.Dictionary2[System.String,System.Int32],(none)(映射自 System.Collections.Generic.IDictionary
2[System.String,System.Int32],(无)) ---> System.InvalidOperationException:类型 Dictionary`2 有多个长度为 2 的构造函数。无法消除歧义。
因此看起来它已找到要解析的类型(为 Dictionary
),但失败更新它...
为什么unity不能解决这种类型?如果我输入
IDictionary<string, int> d = new Dictionary<string, int>()
有效...
有什么想法吗?
谢谢!
I've just stumbled upon this:
within a Unity container, I want to register IDictionary<TK, TV>
; assume that it's IDictionary<string, int>
_unityContainer = new UnityContainer()
.RegisterType<IDictionary<string, int>, Dictionary<string, int>>();
but if I try
var d = _unityContainer.Resolve<IDictionary<string, int>>();
it fails to resolve...
I get...
Microsoft.Practices.Unity.ResolutionFailedException: Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "System.Collections.Generic.IDictionary`2[System.String,System.Int32]", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type Dictionary`2 has multiple constructors of length 2. Unable to disambiguate.
At the time of the exception, the container was:
Resolving System.Collections.Generic.Dictionary2[System.String,System.Int32],(none) (mapped from System.Collections.Generic.IDictionary
2[System.String,System.Int32], (none))
---> System.InvalidOperationException: The type Dictionary`2 has multiple constructors of length 2. Unable to disambiguate..
So it looks like it has found the Type to resolve (being Dictionary<string, int>
) but failed to new it up...
How come unity can't resolve this type? If I type
IDictionary<string, int> d = new Dictionary<string, int>()
that works...
any ideas?
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
非常有趣的发现+1。似乎是 Unity 中的一个错误,请参见此处:
http://unity.codeplex.com /Thread/View.aspx?ThreadId=30292
您还可以尝试以下操作:
这使其使用默认构造函数,从而避免了该问题...
Very interesting find +1. Seems like a bug in Unity, see here:
http://unity.codeplex.com/Thread/View.aspx?ThreadId=30292
You can also try this:
That makes it use the default constructor, thus circumventing the issue...