(譯)Windsor入門教程---第二部分 引用Windsor

來源:互聯網
上載者:User

標籤:style   c   class   blog   code   tar   

介紹

    在第一部分我們建立了一個mvc應用程式,並且已經添加了Windsor,但是還沒有使用它。為了使用Windsor我們需要在應用程式中添加引用。首先我們來看的是控制器工廠,我們將用它來管理我們的控制器和所有其他的依賴項。

控制器工廠

    和其他架構不同,IoC容器就像是一個網路系統管理員。如果它不出錯(前提是你正確的使用),你都不會注意到它。換句話說,我們不會直接的去調用容器也不會和它的API互動,就像你平時根本沒注意到你使用了Tlog架構、表現層架構(例如:ASP.NET MVC)或者是持久性架構(例如:NHibernate)。

    控制器工廠是處理任何與容器顯式互動的地方(除了我們會在Global.asax檔案中引導容器)。這的確人很多人感到驚訝並難以致信,如果你也不信,那麼請相信我的話的,你會看到它是如何工作,如何利用控制反轉(模式)來讓這一切成為可能!

    

    控制器工廠是一個底層類,甚至你從來沒有在你的代碼裡調用過。為了顯示的調用,我在解決方案裡添加了 Plumbing 檔案夾,並且在此檔案夾裡添加了一個WindsorControllerFactory.cs類,這個類繼承了MVC的預設控制器工廠類DefaultControllerFactory,並且重寫了它的兩個方法:

 1 using Castle.MicroKernel; 2 using System; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Web; 6 using System.Web.Mvc; 7 using System.Web.Routing; 8  9 namespace WindsorTutorial.Plumbing10 {11 public class WindsorControllerFactory : DefaultControllerFactory12 {13 private readonly IKernel kernel;14 public WindsorControllerFactory(IKernel kernel)15 {16 this.kernel = kernel;17 }18 public override void ReleaseController(IController controller)19 {20 kernel.ReleaseComponent(controller);21 }22 protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)23 {24 if (controllerType == null)25 {26 throw new HttpException(404, string.Format("The controller for path ‘{0}‘ could not be found.", requestContext.HttpContext.Request.Path));27 }28 return (IController)kernel.Resolve(controllerType);29 }30 }31 } 
View CodeWindsor控制器工廠

    控制器工廠有兩個職責:1、為mvc運行時提供每一次請求的控制器實力;2、當請求結束後釋放控制器。為此我們使用基於Ikernel的Windsor,一個我們使用Windsor為我們處理服務介面,同時在我們使用完畢之後釋放他們。

    我們使用工廠的基類We leverage the base implementation of the factory to figure out based on the route which controller type should handle the request,在某些情況下,當編譯器找不到控制器而報錯的時候,我們會返回404錯誤,同時還會釋放控制器。

提示

    在這一部分,我們在應用程式中建立了一個控制器工廠利用Windsor來管理組件。在下一部分我們會將它整合到我們的應用程式,將組件管理交給Windsor。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.