大家都知道,Castle的Windsor容器非常強大,可以橫向擴充的先進架構和自持自動連接等進階功能,並且充分利用了.Net的優勢和特點,非常值得學習研究。
在Castle中添加和使用組件非常簡單:1IWindsorContainer container = new WindsorContainer( new XmlInterpreter("../BasicUsage.xml") );
2
3container.AddComponent( "newsletter",
4 typeof(INewsletterService), typeof(SimpleNewsletterService) );
5container.AddComponent( "smtpemailsender",
6 typeof(IEmailSender), typeof(SmtpEmailSender) );
7container.AddComponent( "templateengine",
8 typeof(ITemplateEngine), typeof(NVelocityTemplateEngine) );
9
這樣就可以了,不需要像Spring.Net那樣寫串連設定檔,因為在Castle中組件之間的依賴關係是自動檢測並串連的。
那麼,Castle是如何做到的呢?
當AddComponent的時候,Windsor其實是調用了MicroKernel來進行註冊,Windsor只是MicroKernel的一個封裝,容器的主要功能其實都是MicroKernel完成的,而MicroKernel被設計成一個非常精巧,但是可擴充能力超強的一個核心結構。
在MicroKernel中,添加一個組件的具體的代碼如下:public virtual void AddComponent(String key, Type serviceType, Type classType)
{
if (key == null) throw new ArgumentNullException("key");
if (serviceType == null) throw new ArgumentNullException("serviceType");
if (classType == null) throw new ArgumentNullException("classType");
ComponentModel model = ComponentModelBuilder.BuildModel(key, serviceType, classType, null);
RaiseComponentModelCreated(model);
IHandler handler = HandlerFactory.Create(model);
RegisterHandler(key, handler);
}
首先,ComponentModelBuilder給組件產生了一個ComponentModel,這個Model實際上是用大量的反射來捕獲這個組件的各種詳細的元資訊,就好象先給你來一次X光掃描,這個組件是什麼東西清清楚楚。
建立模型的具體過程如下:
public ComponentModel BuildModel(String key, Type service, Type classType, IDictionary extendedProperties)
{
ComponentModel model = new ComponentModel(key, service, classType);
if (extendedProperties != null)
{
model.ExtendedProperties = extendedProperties;
}
foreach(IContributeComponentModelConstruction contributor in contributors)
{
contributor.ProcessModel( kernel, model );
}
return model;
}
其實具體過程就是調用contributor來進行具體的資訊收集,每個Contributor負責收集不同的資訊,在DefaultMicroKernel中一共註冊了以下7個Contributor來收集資訊:
protected virtual void InitializeContributors()
{
AddContributor( new ConfigurationModelInspector() );
AddContributor( new LifestyleModelInspector() );
AddContributor( new ConstructorDependenciesModelInspector() );
AddContributor( new PropertiesDependenciesModelInspector() );
AddContributor( new LifecycleModelInspector() );
AddContributor( new ConfigurationParametersInspector() );
AddContributor( new InterceptorInspector() );
}
他們各有各的功能,你可以可以自己寫Contributor來收集你想要收集的資訊。
接下來就是發出ComponentCreated的事件,這個事件是一個容器的擴充點,可以被註冊的Facility接收到。
再接下來,就是調用HandlerFactory來建立一個IHandler,IHandler的主要功能就是建立組件的啟用器(Activator),每個組件都對應一個Activator,Activator根據Lifestyle管理器來建立不同生命類型的組件執行個體,比如Singleton,PreThread,Transient等等。
然後在EnsureDependenciesCanBeSatisfied()這個方法中檢查組件的依賴是否都得到了滿足,這裡就是自動連接的原理,假如沒有滿足,Castle就迴圈檢查以前註冊的每個組件是否滿足該組件的要求,或者該組件是否滿足以前註冊的組件的要求,假如滿足就添加到組件的依賴列表中。
最後,註冊IHandler,激發Registed事件(另一個擴充點),完成整個組件的註冊過程。