2009-12-30 23 views
3

這是由框架生成的默認AccountController.cs爲什麼MVC提供的Default AccountController中有2個構造函數?

public class AccountController : Controller 
{ 
    public IFormsAuthentication FormsAuth { get; private set; } 
    public IMembershipService MembershipService { get; private set; } 

    public AccountController() 
     : this(null, null) 
    { 
    } 
    public AccountController(IFormsAuthentication formsAuth, IMembershipService membershipService) 
    { 
     FormsAuth = formsAuth ?? new FormsAuthenticationService(); 
     MembershipService = membershipService ?? new AccountMembershipService(); 

     //--- 
    } 

這很容易理解。

public AccountController(IFormsAuthentication formsAuth, 
     IMembershipService membershipService) 
    { 
     FormsAuth = formsAuth ?? new FormsAuthenticationService(); 
     MembershipService = membershipService ?? new AccountMembershipService(); 
    } 

這是什麼?它的目的是什麼?對於賬戶管理員來說是特別的還是對其他控制器的要求?並且,爲什麼我應該將其納入我的項目?

public AccountController() 
     : this(null, null) 
    { 
    } 

他們似乎在另外兩個地方使用這種類型的構造函數。

感謝您的幫助

回答

0
  1. 如果使用DI框架(如統一),並通過集裝箱你主動的控制器,它可能無法找到的依賴關係,並使用默認的構造函數(在這種情況下)。

  2. 如果你想使用使用泛型,像... where T : IController, new()之類的東西,你將需要一個默認的構造函數。

7

這實際上是庶子注射反模式的實行。

想法是構造函數注入支持依賴注入(DI),同時仍爲缺省行爲提供默認構造函數。

確實沒有必要擁有默認構造函數,但是如果省略它,則必須提供自定義IControllerFactory,因爲DefaultControllerFactory假定所有控制器都具有默認構造函數。

ASP.NET MVC是以DI爲基礎構建的,但我猜想爲了保持簡單,Bastard Injection模式被用於項目模板,以避免在開發人員面前強制使用特定的IControllerFactory。

0

擁有默認(無參數)構造函數的另一個原因是Reflection

在System.Reflection命名空間中的類,有型起來,讓你獲得它們內部定義加載assemblies和類型,如classesinterfacesvalue types信息。您還可以使用反射在運行時創建類型實例,並調用和訪問它們。

在某些情況下,您需要創建該類型的臨時對象以反映其屬性或方法,但不希望或需要創建實際對象的開銷 - 尤其是如果這需要例如訪問數據庫或遠程服務。

相關問題