Search code examples
dependency-injectionunity-containerconstructor-injection

Is it possible to inject parameters into protected constructors using Unity?


I can do this in Castle Windsor:

public abstract class AbstractFactory
{
    protected AbstractFactory(Foo constructorParm)
    {
        // Do something with parameter...
    }
}

public class DescendentFactory : AbstractFactory
{
    public DescendentFactory(Foo constructorParm) : base(constructorParm)
    {
    }
}

// The container is configured via XML, the service AbstractFactory and the
// type DescendentFactory
container.Resolve<AbstractFactory>("DescendentFactoryId", new { constructorParm = injectedValue });

Is this possible in Unity? I've tried doing it but it complains that it can't find the constructor. It seems I can only inject via the sub-type.


Solution

  • You can only inject via the sub-type. It needs a public constructor.