![](/img/trans.png)
[英]Unity: how to specify to use specific instance of a type when resolving another type
[英]How can I specify a constructor for Unity to use when resolving a service?
我有以下構造函數:
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使用我的兩個構造函數之一?
一種方法是使用InjectionConstructorAttribute注釋所需的構造函數:
當一個目標類包含多個具有相同數量參數的構造函數時,必須將InjectionConstructor屬性應用於該構造函數
樣品:
[InjectionConstructor]
public ReferenceService(IAzureTable<Reference> referenceRepository)
{
_referenceRepository = referenceRepository;
}
public ReferenceService(CloudStorageAccount devStorageAccount)
{
_referenceRepository = new AzureTable<Reference>(devStorageAccount, "TestReferences");
}
container.RegisterType<IReferenceService, ReferenceService>();
更改為
container.RegisterType<IReferenceService, ReferenceService>(new InjectionConstructor());
如果要使用不帶參數的那一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.