2016-03-17 143 views
3

我對依賴注入非常陌生,我剛剛設置了Unity.Mvc5,並且取得了一些成功。但是現在我面臨着控制器類中多個構造器的問題。我已經有處理我的UserManager和以下教程的構造函數我明白我需要另一個構造函數來實例化我的接口。當我這樣做不過,我得到以下錯誤:使用Unity.Mvc5注入依賴關係時的多個控制器構造函數

The type OrganisationController has multiple constructors of length 1. Unable to disambiguate.

從我的控制器的代碼段:

private IPush _pushMessage; 

    // Here is the problem! 
    public OrganisationController(IPush pushMessage) 
    { 
     _pushMessage = pushMessage; 
    } 

    public OrganisationController() 
     : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))) 
    { 
    } 

    public OrganisationController(UserManager<ApplicationUser> userManager) 
    { 
     UserManager = userManager; 
     var provider = new DpapiDataProtectionProvider("MyApp"); 
     UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("PasswordReset")); 
    } 

    public UserManager<ApplicationUser> UserManager { get; private set; } 

而且我作爲UnityConfig.cs如下:

public static class UnityConfig 
{ 
    public static void RegisterComponents() 
    { 
     var container = new UnityContainer(); 

     container.RegisterType<IPush, PushMessage>(); 
     container.RegisterType<IController, OrganisationController>(); 
     container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(); 
     container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager()); 

     DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 
    } 
} 

我不知道怎麼樣告訴Unity我有另一個構造函數被用來實現一個接口。

+0

嘗試用[InjectionConstructor]屬性標記要用於DI的ctor。這將允許統一識別哪個ctor要解決。 – AksharRoop

回答

3

使用DI時,構造函數具體爲,對於 DI。沒有理由創建替代構造函數(尤其是在控制器上,因爲唯一的調用者是將該調用委託給DI容器的ControllerFactory)。其實using multiple constructors with dependency injection is anti-pattern應該避免。

相關:Rebuttal: Constructor over-injection anti-pattern

+0

接受這個答案,不是因爲它解決了我確切的問題,而是因爲它消除了我的問題的根本原因。我已經刪除了其他構造函數,並在其他地方實例化了UserManager。謝謝你的信息。 –

1

雖然我通過@ NightOwl888其他答案達成一致。在某些情況下,你可能想要有多個構造函數。

你有沒有試過InjectionConstructor屬性?

[InjectionConstructor] 
public OrganisationController(IPush pushMessage) 
{ 
    _pushMessage = pushMessage; 
} 
相關問題