您的位置:首页 > 其它

Castle的IoC容器深入分析

2005-08-02 15:44 337 查看
大家都知道,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事件(另一个扩展点),完成整个组件的注册过程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: