container icon indicating copy to clipboard operation
container copied to clipboard

DependencyOverride is ignored during resolution

Open DoctorVanGogh opened this issue 6 years ago • 2 comments

Description

If a constructor argument has a default value registered via InjectionConstructor then a matching DependencyOverride in a Resolve call is ignored.

To Reproduce

    class Program {
        static void Main(string[] args) {

            var container = new UnityContainer();

            container.RegisterType<Foo>(new PerResolveLifetimeManager(),
                                        new InjectionConstructor("default"));

            Console.WriteLine(container.Resolve<Foo>()
                                       .ToString());
            Console.WriteLine(container.Resolve<Foo>(
                                           new DependencyOverride<string>("custom-via-dependencyoverride"))
                                       .ToString());
            Console.WriteLine(container.Resolve<Foo>(
                                           new ParameterOverride(typeof(string), "custom-via-parameteroverride"))
                                       .ToString());
        }
    }


    public class Foo {
        private readonly string _dependency;

        public Foo([Dependency] string dependency) {
            _dependency = dependency;
        }

        public override string ToString() => _dependency;
    }

will output

default
default
custom-via-parameteroverride

Additional context

As shown in the example, ParameterOverride correctly uses the passed override, it's just DependencyOverride which doesn't.

DoctorVanGogh avatar Feb 28 '19 10:02 DoctorVanGogh

Just a heads-up for the change. Starting with 5.9.8 this will no longer work. To override the parameters you'll have to use ParameterOverride.

This is a tutorial on DependencyOverride that explains how it works

ENikS avatar Mar 17 '19 19:03 ENikS

Unity v6 is fixing this issue

ENikS avatar Nov 14 '20 16:11 ENikS