Search code examples
c#dependency-injectionunity-containerconstructor-injection

In the Unity dependency injection framework, is there an equivalent to running BuildUp with InjectionConstructors?


One thing I've always wanted in an DI framework is the ability to use injection constructors with objects that interact with the framework only to consume services. For instance:

public class ServiceClass : IServiceInterface
{
    public string Name { get; set; }
}

public class ConsumerClass // explicitly implements no interfaces
{
    private readonly IServiceInterface service;
    public IServiceInterface Service { get { return service; } }

    [InjectionConstructor]
    public ConsumerClass(IServiceInterface service)
    {
        this.service = service;
    }
}

static void Main()
{
    IUnityContainer container;
    // blah blah DI setup stuff
    container.RegisterType<IServiceInterface, ServiceClass>();

    // Key point here!
    container.Instantiate<ConsumerClass>();
    // Alternatively:
    container.Instantiate(typeof(ConsumerClass));
}

IUnityContainer's BuildUp() method sort of does this, but it requires that you have an instance to pass in, and I can't do this if I want to use injection constructors.

Moreover, I could use:

    container.RegisterType(typeof(ConsumerClass), 
        new InjectionConstructor(container.Resolve<IServiceClass>()));

However, this is a lot of code to be writing--especially for classes that could have several parameters in the constructor--and seems to remove the utility of the container in the first place.

There's also:

    container.RegisterType<ConsumerClass, ConsumerClass>();  

However with this one, I don't actually want to register the type--I just want it to be created with its dependencies filled via the InjectionConstructor.

So in summary: I want to use injection constructors and I want Unity to do the mapping of registered services for me, and if possible I would like to keep my consumers out of the container. Is there a way to do this that I've missed?


Solution

  • As you have discovered, the .BuildUp method only works on existing instances, to create new instances using Unity you want to use the .Resolve methods, these will create the instance injecting any dependencies as and when required.

    For your example use var consumer = container.Resolve<ConsumerClass>() and all of the dependencies will be injected. You do not require any registration for ConsumerClass because it is a concrete type which Unity is able to handle implicitly.