2017-08-22 47 views
0

假設我有這樣的如何在具有構造函數的類上使用Unity實現DI - mvc?

public interface ILienholderBusinessService 
    { 
     string GetCoverage(IList<PolicyVinRequest> InputList); 
    } 

public class LienholderBusinessService : ILienholderBusinessService 
    { 
     public ILienholderPolicySearchDataService LienholderPolicySearchDataService { get; set; } 

     public LienholderBusinessService(ILienholderPolicySearchDataService LienholderPolicySearchDataService) 
     { 
      this.LienholderPolicySearchDataService =LienholderPolicySearchDataService ; 
     } 
     public string GetCoverage(IList<PolicyVinRequest> InputList) 
     { 
      return "my string"; 

     } 
    } 

一個接口和類我有這樣

public class InsuranceVerificationPortalController : Controller 
    { 
     public ILienholderBusinessService LienholderBusinessService { get; set; } 
     public InsuranceVerificationPortalController(ILienholderBusinessService LienholderBusinessService) 
     { 
      this.LienholderBusinessService = LienholderBusinessService; 
     } 
} 

控制器現在,當我試圖實現我的MVC團結,我得到錯誤,如

你是否缺少任何類型

如何在具有構造函數的類上實現使用Unity的DI

回答

1

您必須爲需要解析具體類型的所有接口註冊映射。從公佈的代碼,這將是ILienholderBusinessServiceILienholderPolicySearchDataService

container.RegisterType<ILienholderBusinessService, LienholderBusinessService>(); 
container.RegisterType<ILienholderPolicySearchDataService, LienholderPolicySearchDataService>(); 

這可能是的ILienholderPolicySearchDataService的實施還取決於接口/抽象類(如IRepository<T>)。如果是這種情況,則需要爲這些映射創建映射。

默認情況下,Unity將選擇參數數量最多的構造函數,因此如果需要選擇另一個構造函數,可以使用InjectionConstructor。例如

container.RegisterType<ILienholderPolicySearchDataService, LienholderPolicySearchDataService>(
    new InjectionConstructor(typeof(IRepository<Policy>))); 
相關問題