2009-09-18 80 views
2

我有一個應用程序,仿照從Apress的臨ASP.NET MVC使用溫莎城堡的IoC實例有各自的資料庫控制器的一個,這是工作的罰款ASP.NET MVC使用溫莎城堡的IoC

例如

public class ItemController : Controller 
{ 
    private IItemsRepository itemsRepository; 
    public ItemController(IItemsRepository windsorItemsRepository) 
    { 
     this.itemsRepository = windsorItemsRepository; 
    } 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using Castle.Windsor; 
using Castle.Windsor.Configuration.Interpreters; 
using Castle.Core.Resource; 
using System.Reflection; 
using Castle.Core; 

namespace WebUI 
{ 
    public class WindsorControllerFactory : DefaultControllerFactory 
    { 
     WindsorContainer container; 

     // The constructor: 
     // 1. Sets up a new IoC container 
     // 2. Registers all components specified in web.config 
     // 3. Registers all controller types as components 
     public WindsorControllerFactory() 
     { 
      // Instantiate a container, taking configuration from web.config 
      container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle"))); 

      // Also register all the controller types as transient 
      var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes() 
            where typeof(IController).IsAssignableFrom(t) 
            select t; 
      foreach (Type t in controllerTypes) 
       container.AddComponentWithLifestyle(t.FullName, t, LifestyleType.Transient); 
     } 

     // Constructs the controller instance needed to service each request 
     protected override IController GetControllerInstance(Type controllerType) 
     { 
      return (IController)container.Resolve(controllerType); 
     } 
    } 
} 

控制控制器創建。

我有時需要在控制器內創建其他存儲庫實例,從其他地方獲取數據,我可以使用CW IoC來完成這項工作嗎?如果是,那麼該怎麼做?

我一直在玩新控制器類的創建,因爲它們應該自動註冊我的現有代碼(如果我可以得到這個工作,我可以稍後正確註冊它們),但是當我嘗試實例化它們時是一個明顯的反對意見,因爲我無法爲構造函數提供一個repos類(我確信這是無論如何都是錯誤的方式)。

任何幫助(特別是例子)將不勝感激。 乾杯 MH

+0

你最後的結論是什麼?我有同樣的設計問題。 – Jon 2011-01-14 12:46:00

+0

看了這個之後不久,我在應用程序中發現了一處內存泄漏,它來自Castle Windsor代碼中的某個地方(無論是我使用它的方式是否正確,我不知道,但是我是在使用它簡單的水平,所以我不是100%確定它_was_我),所以我沒有得到解決這些解決方案 - 對不起。如果你嘗試下面的解決方案,它的工作原理,請讓我知道,我會標記爲正確的。 – 2011-01-18 09:39:31

回答

1

獲取(以及更多),它不`噸工作了王氏windor城堡的最後一個版本,其實,微內核裝配在城堡內部融化.Core

+0

你的黃花魚內爾在城堡裏面融化了嗎?聽起來像一個特洛伊木馬,我的意思是青蛙。 – 2013-12-24 23:13:40

5

剛剛宣佈在你的控制器構造您需要的依賴,即:

public class MyController: Controller { 
    private readonly IItemsRepository itemsRepo; 
    private readonly IPersonRepository personRepo; 
    public MyController(IItemsRepository i, IPersonRepository p) { 
    itemsRepo = i; 
    personRepo = p; 
    } 
} 

溫莎會自動解決依賴性,當它實例化控制器。

有很多關於谷歌代碼的項目可以用於指導,例如WineCellarManager

BTW:你不需要編寫自己的WindsorControllerFactory,你可以從MVCContrib

+0

這並不總是實用的,例如在對象驗證規則中,我需要檢查針對主DB添加的任何零件編號 - 最好在對象中執行此操作,因爲它使業務邏輯遠離控制器,但對象不會沒有回購(我也不是真的想創建一個,除非我需要檢查數據) – 2009-09-24 11:32:42

+0

驗證與此無關......請爲此創建另一個問題 – 2009-09-24 12:10:47

+0

它的確如此,因爲在我的驗證規則中,我需要訪問數據庫回購。 – 2009-09-24 13:20:04