With Unity how do I inject a named dependency into a constructor?

You can configure dependencies with or without names in the API, attributes, or via the config file. You didn’t mention XML above, so I’ll assume you’re using the API.

To tell the container to resolve a named dependency, you’ll need to use an InjectionParameter object. For your ClientModel example, do this:

container.RegisterType<IClientModel, ClientModel>(
    new InjectionConstructor(                        // Explicitly specify a constructor
        new ResolvedParameter<IRepository>("Client") // Resolve parameter of type IRepository using name "Client"
    )
);

This tells the container “When resolving ClientModel, call the constructor that takes a single IRepository parameter. When resolving that parameter, resolve with the name ‘Client’ in addition to the type.”

If you wanted to use attributes, your example almost works, you just need to change the attribute name:

public ClientModel([Dependency("Client")] IRepository dataAccess)
{
   this.dataAccess = dataAccess;

   .....
}

Leave a Comment