2

我有以下構造函數:如何在指定解析服務時使用Unity的構造函數?

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>(); 

當我嘗試有統一解決我的服務它給了我一個錯誤信息說有不止一個構造一個參數:

[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

一種方法是註釋你想用InjectionConstructorAttribute構造:

當目標類包含一個以上的構造與相同數量的參數,則必須將InjectionConstructor屬性應用到構造

樣品:

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

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

嘗試InjectionConstructor

container.RegisterType<IReferenceService, ReferenceService>(); 

變化

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

,如果你想使用一個不帶參數。

相關問題