Search code examples
c#inversion-of-controlunity-container

How to tag additional parameter onto constructor and inject dependencies using Unity?


I have a host service with 2 service interface dependencies, but I would like to tag a 3rd string parameter in the constructor. Currently the first 2 are already registered so are supplied correctly when resolving.

Depending on whether my service boots-up from command line or command host (using TopShelf), I want to be able to inject a 3rd value from the command line, either supply empty if not supplied or call the constructor with just the 2 interface dependencies.

I've seen the ParameterOverride() class but I don't want to have re-define the first 2 parameters again if these are already registered. I'm also not sure how Unity can pick either the greedy constructor or the slim one depending if the parameter exists.

e.g.

  public HostService(ISchedulerService schedulerService,
                     IConfigService configService,
                     string commandLineValue)
        { }

How do I get Unity to inject the services as normal but also supply the 3rd value?

container.RegisterType<IHostService, HostService>();

Solution

  • At this MSDN page, there is a solution for when you need to add a parameter to a constructor:

    container.RegisterType<HostService>(new InjectionConstructor(parameter1, parameter2, parameter3))
    

    I would also investigate whether this works:

    1. Add another constructor without the commandLineValue parameter (constructor overloading) or:
    2. Set the commandLineValue parameter with a default value

    as in:

    public HostService(ISchedulerService schedulerService, IConfigService configService, string commandLineValue = string.Empty)
    {}
    

    so there is no need to provide the third parameter.