2010-03-02 16 views
1

我打開其他IoC容器,如NInject和StructureMap,如果它們比這更清潔。我聽說StructureMap剛剛引入了「容器」,可能會簡化這個問題?有沒有更好的方法將Castle Windsor的API用於工廠?

正如標題所說,有沒有更好的方法?這看起來像很多代碼,只是爲了註冊一個需要工廠來創建它的對象。

// The process to register an object, with a factory method 
var cfg = new MutableConfiguration(p.Name); 
cfg.Attributes["factoryId"] = p.TypeFactory.Name; 
cfg.Attributes["factoryCreate"] = "Create"; 
var model = _container.Kernel.ComponentModelBuilder.BuildModel(
    p.Name, p.TypeService, p.Type, null); 
model.LifestyleType = LifestyleType.Pooled; 
model.Configuration = cfg; 
_container.Kernel.AddCustomComponent(model); 

添加或黑白的部件的 「非工廠」 的方式:

// registering a component with no factory method 
_container.AddComponentLifeStyle(
    p.Name, p.TypeService, p.Type, LifestyleType.Singleton); 

第一似乎過於複雜。

在此先感謝!

+0

您是否考慮在發佈此文檔之前檢查文檔? http://using.castleproject.org/display/IoC/Fluent+Registration+API#FluentRegistrationAPI-Usingadelegateascomponentfactory: – 2010-03-03 07:51:44

+0

plus也FactorySupportFacility類有方法來幫助這個,如果你不想流利的API。你基本上選擇了這樣做的最不理想的方式。 – 2010-03-03 07:53:49

+0

你好Krzysztof,並感謝您的意見。有趣的是,我從來沒有見過鏈接到城堡的文檔 - 因爲任何鏈接都是這樣的網頁:http://api.castleproject.org/直接從他們的網站。感謝您將我與實際文檔聯繫起來(但請在將來的評論中保持仁慈)。 – eduncan911 2010-03-03 17:34:43

回答

3

我不確定你想要註冊什麼(p在第一個代碼塊?),但UsingFactoryMethod,工廠註冊是一件輕而易舉的事情。示例代碼:

container.AddFacility<FactorySupportFacility>() 
    .Register(
     Component.For<IMyService>() 
     .UsingFactoryMethod(() => MyLegacyServiceFactory.CreateMyService()) 
     .LifeStyle.Pooled 
    ); 
+0

你好再次Mauricio!哇,這確實簡化了事情。作爲對上述問題的評論,儘管主要的castleproject站點指出了這一點,但似乎有不同的文檔位置:http://api.castleproject.org/謝謝。標記爲答案。哦,「p」來自Linq查詢。應該不重要。 – eduncan911 2010-03-03 17:35:39

+1

IOU下載頁面改進。我沒有忘記:) – 2010-03-03 18:23:57

相關問題