Search code examples
dependency-injectionunity-container

How to resolve type with parameter and use this parameter when resolving in child dependencies


In Unity, is it possible to resolve a type with a parameter then furthermore inject this specific parameter in child dependencies?

E.g Parent has constructor with parameter Dummy. Parent resolves several other types which also has a Dummy parameter in their constructors - in which I want the specific parameter injected.

Possible?


Solution

  • Given you provide the parameter at resolve-time, this is the default behaviour.

    In this example, "dummyValue" is injected into both constructors (MyImplementation and MySomething):

    class Program
    {
        static void Main( string[] args )
        {
            var container = new UnityContainer();
            container.RegisterType<IInterface, MyImplementation>();
            container.RegisterType<ISomething, MySomething>();
            var instance = container.Resolve<MyImplementation>( new ParameterOverride( "dummy", "dummyValue" ) );
        }
    }
    
    internal class MyImplementation : IInterface
    {
        public MyImplementation( ISomething dep, string dummy )
        {
        }
    }
    
    internal class MySomething : ISomething
    {
        public MySomething( string dummy )
        {
        }
    }
    
    internal interface IInterface
    {
    }
    
    internal interface ISomething
    {
    }