2

我有以下构造函数:

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

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

在 Bootstrapper.cs 中

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

当我尝试让 Unity 解析我的服务时,它会给我一条错误消息,指出有多个构造函数具有一个参数:

[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))
]

有没有办法强制 Unity 使用我的两个构造函数之一?

4

2 回答 2

4

一种方法是使用InjectionConstructorAttribute注释您想要的构造函数:

当一个目标类包含多个具有相同参数数量的构造函数时,必须将 InjectionConstructor 属性应用于构造函数

样本:

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

public ReferenceService(CloudStorageAccount devStorageAccount)
{
    _referenceRepository = new AzureTable<Reference>(devStorageAccount, "TestReferences");
}
于 2012-11-11T03:29:38.243 回答
2

试试InjectionConstructor

container.RegisterType<IReferenceService, ReferenceService>();

更改为

container.RegisterType<IReferenceService, ReferenceService>(new InjectionConstructor());

如果你想使用没有参数的那个。

于 2012-11-11T03:27:56.717 回答