2013-05-08 52 views
2

我想了解如何在mvc中調用控制器和操作。 經過大量閱讀後,我發現ExecuteCore()方法得到執行,它存在於Controller.cs類中。ASP.NET MVC中的ExecuteCore()方法

protected override void ExecuteCore() 
{ 
    // If code in this method needs to be updated, please also check the BeginExecuteCore() and 
    // EndExecuteCore() methods of AsyncController to see if that code also must be updated. 

    PossiblyLoadTempData(); 
    try 
    { 
     string actionName = RouteData.GetRequiredString("action"); 
     if (!ActionInvoker.InvokeAction(ControllerContext, actionName)) 
     { 
      HandleUnknownAction(actionName); 
     } 
    } 
    finally 
    { 
     PossiblySaveTempData(); 
    } 
} 

public IActionInvoker ActionInvoker 
{ 
    get 
    { 
     if (_actionInvoker == null) 
     { 
      _actionInvoker = CreateActionInvoker(); 
     } 
     return _actionInvoker; 
    } 
    set { _actionInvoker = value; } 
} 

protected virtual IActionInvoker CreateActionInvoker() 
{ 
    // Controller supports asynchronous operations by default. 
    return Resolver.GetService<IAsyncActionInvoker>() ?? Resolver.GetService<IActionInvoker>() ?? new AsyncControllerActionInvoker(); 
} 

當ExecuteCore()開始執行時,對ActionInvoker屬性的引用將其返回給IActionInvoker類型。

IActionInvoker由AsyncControllerActionInvoker.cs類實現,該類中實現了InvokeAction(ControllerContext,actionName)方法。

所以我的問題是:

  1. 如何IActionInvoker接口被實例化在這裏,和ActionInvoker屬性返回?
  2. 對屬性的引用是否返回AsyncControllerActionInvoker類的對象,以便我們可以使用該對象調用InvokeAction(ControllerContext,actionName)方法。
  3. Resolver.GetService<IAsyncActionInvoker>()Resolver.GetService<IActionInvoker>()做什麼?

請幫我理解這一點。

回答

1

ASP.NET有一種內置的依賴注入。

這意味着,不是對特定類有一個硬引用,而是控制器引用了接口。 Resolver然後被配置爲在請求實例時返回某種類型。例如(示例代碼,我不知道確切的方法名)

Resolver.Bind<IActionInvoker>().To<ActionInvoker>(); // if an IActionInvoker is requested, return an instance of type ActionInvoker. 

此配置後GetService通話將讓你的ActionInvoker

實例因此,要回答你的問題:

  1. IActionInvoker接口如何在此實例化,並由ActionInvoker屬性返回?

通過前手配置旋轉變壓器,所述旋轉變壓器知道創建哪一類,並返回

  1. 是否參考屬性返回AsyncControllerActionInvoker類的一個對象,以便我們可以使用該對象調用InvokeAction(ControllerContext,actionName)方法。

是,也不是。是的,酒店將確保您擁有一個實施IActionInvoker 的物品,您可以使用該物品致電InvokeAction。不,你不能保證它是IAsyncActionInvoker類型的(取決於解析器的配置)

  1. 什麼不Resolver.GetService()和Resolver.GetService()呢?

他們要求解析器實例化一個實現給定接口的對象。解析器將查找其配置中的接口,實例化適當的對象並將其返回給調用者。

依賴注入是一種解耦代碼的方式。由於您只引用了接口,因此您沒有硬性依賴關係,您可以重新配置DI容器(在本例中爲Resolver),並且您將使用另一個類,而您的客戶類無需知道它。

+0

很多很多感謝,對我理解這個話題非常有幫助。你能否告訴我一些鏈接,我可以從這裏瞭解更多關於這個主題的內容,以及關於構建在依賴注入中的ASP.NET? – Bibhu 2013-05-09 11:56:04