2011-09-06 22 views
2

我需要Castle.Windsor的每個請求生活方式。這不是一個ASP應用程序,並且本機PerWebRequest生活方式將不起作用。Castle.Windsor每個請求的生活方式:subcontainers vs定製生活方式

加工前我做一個請求(每個請求):代碼

MyContainer = new Container(); 
MyContainer.Register(
    Component.For<ICache>().ImplementedBy<Cache>().LifeStyle.Singleton 
    ); 
MyMainStaticContainer.AddChildContainer(MyContainer); 
//MyMainStaticContainer contains implementations which 
//can be shared across requests 

然後某處:

MyContainer.Resolve<ICache>().Items.Add("x", "y"); 
... 
MyContainer.Resolve<ICache>().Items.Get("x"); 

最後,當工作完成(在ASP它會在Application_EndRequest)

MyContainer.Parent.RemoveChildContainer(MyContainer); 
MyContainer.Dispose(); 

這是相當優雅的(如:不是很多步驟,很容易理解d)它適用於我,但如果執行習慣生活方式會更好(更安全?,更高效?),我很好奇。

由於提前,

Tymek

回答

0

您是否嘗試過 「瞬態」?

此鏈接可以幫助您選擇適合您的需要是正確的:CastleProject - Lifestyles

注:爲了節省您在每次請求註冊這一點,你可能想在溫莎的ID的優勢的.config。 ID將允許您有多個ICache實現,並且可以使用Interface-ID組合鍵將它們從Windsor中提取出來。

在Windsor.config

<component id="MyDefaultCache" 
      service="MyAssembly.ICache, MyAssembly" 
      type="MyAssembly.MyDefaultCache, MyAssembly" /> 
<component id="MySpecialCache" 
      service="MyAssembly.ICache, MySpecialCache" 
      type="MySpecialAssembly.MySpecialCache, MySpecialAssembly" /> 

及代碼:

MyContainer.Resolve<ICache>("MySpecialCache") 

第一個總是默認的,所以MyContainer.Resolve<ICache>將解析爲MyAssembly.MyDefaultCache

相關問題