views:

339

answers:

1

Hi,

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!

+1  A: 

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...

BFree
thanks for the thread and the suggestion - I guess I'll need to write a non-generic wrapper for the Dictionary, which is just another level of complexity i could've done without :( - thanks again
IanR
@BFree - sincere apologies for the delay on accepting this one... I've only just caught up with you on the InjectionConstructor suggestion, which indeed circumvents the issue... marking as accepted now - thanks :)
IanR