Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot resolve Dictionary in Unity container

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.IDictionary2[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!

like image 346
kiwipom Avatar asked Apr 29 '10 00:04

kiwipom


1 Answers

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:

 container.RegisterType<IDictionary<int, string>, Dictionary<int, string>>
                (new InjectionConstructor());

That makes it use the default constructor, thus circumventing the issue...

like image 117
BFree Avatar answered Oct 22 '22 23:10

BFree