unitycontainer / microsoft-dependency-injection

Unity.Microsoft.DependencyInjection package
Apache License 2.0
63 stars 36 forks source link

Problem with IEnumerable string resolving after Unity.Container dep 5.9.0 #78

Closed michael-dots closed 4 years ago

michael-dots commented 4 years ago

Hi,

I'm having trouble with resolving IEnumerable strings if a string is also registered, this must surely be a bug?

I discovered the problem when updating from an old version to the newest, and narrowed it down to between Unity.Container 5.8.13 and 5.9.0.

Reproduction code, .net core console:

        static void Main(string[] args)
        {
            var container = new UnityContainer();
            List<string> ApplesBefore = new List<string>(), ApplesAfter = new List<string>();
            string Username = "Why";

            try
            {
                ApplesBefore = container.Resolve<List<string>>("Apple");
            }
            catch (Exception)
            {
            }

            container.RegisterInstance<string>("Username", Username);

            try
            {
                ApplesAfter = container.Resolve<List<string>>("Apple");
            }
            catch (Exception)
            {
            }

            Console.WriteLine("Before = " + ApplesBefore.Count + ", After = " + ApplesAfter.Count + " / " + String.Join(',', ApplesAfter));

            Console.ReadLine();
        }

After 5.9.0: Before = 0, After = 1 / Why

Before 5.9.0: Before = 0, After = 0 /

Sorry if this is the wrong issue tracker, I found some similar closed cases here so assume it's the right place.

ENikS commented 4 years ago

Duplicate unitycontainer/unity#314

ENikS commented 4 years ago

This behavior is mandated by Microsoft Dependency Injection specification. It would not pass compatibility tests without it.

You could stop this behavior by registering List<> with constructor of your choice specified by InjectionConstructor

container.RegisterType(typeof(List<>), new InjectionConstructor())
container.RegisterType(typeof(IList<>), typeof(List<>), new InjectionConstructor())