Search code examples
c#.netinversion-of-controlunity-containerconstructor-injection

How can I specify a constructor for Unity to use when resolving a service?


I have the following constructors:

public ReferenceService(
    IAzureTable<Reference> referenceRepository)
{
    _referenceRepository = referenceRepository;
}

public ReferenceService(CloudStorageAccount devStorageAccount)
{
    _referenceRepository = new AzureTable<Reference>(devStorageAccount, "TestReferences");
}

and in Bootstrapper.cs

CloudStorageAccount storageAccount;
        storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
        var container = new UnityContainer();
        container.RegisterType<IReferenceService, ReferenceService>();

When I try to have Unity resolve my service it gives me an error message saying there's more than one constructor with one parameter:

[ResolutionFailedException: Resolution of the dependency failed, type = "WebUx.xController", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type ReferenceService has multiple constructors of length 1. Unable to disambiguate.
-----------------------------------------------
At the time of the exception, the container was:

  Resolving WebUx.xController,(none)
  Resolving parameter "referenceService" of constructor WebUx.xController(
Storage.Services.IContentService contentService,  
Storage.Services.IReferenceService referenceService
)
    Resolving Storage.Services.ReferenceService,(none) (mapped from Storage.Services.IReferenceService, (none))
]

Is there a way I can force Unity to use one of my two constructors?


Solution

  • One way is to annotate the constructor you want with an InjectionConstructorAttribute:

    When a target class contains more than one constructor with the same number of parameters, you must apply the InjectionConstructor attribute to the constructor

    Sample:

    [InjectionConstructor]
    public ReferenceService(IAzureTable<Reference> referenceRepository)
    {
        _referenceRepository = referenceRepository;
    }
    
    public ReferenceService(CloudStorageAccount devStorageAccount)
    {
        _referenceRepository = new AzureTable<Reference>(devStorageAccount, "TestReferences");
    }