大家都知道,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 那么,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来收集你想要收集的信息。
|
|