技术开发 频道

Castle IOC容器实践之Startable Facility(二)


【IT168技术文档】

  摘要:在Castle IOC容器实践之Startable Facility(一)中我们已经学会了如何去使用Startable Facility,本文将在此基础进一步对它的原理做一些分析。



  主要内容

  Startable Facility原理分析


  在Castle IOC容器实践之Startable Facility(一)中我们已经看到了如何去使用Startable Facility,本文将对它的原理做一些分析。先看一下接口IStartable,它的实现代码如下:
public interface IStartable { void Start(); void Stop(); }
  代码是相当的简单,只有两个方法,分别在组件创建的时候和销毁的时候执行,这就涉及到了组件的生命周期管理。在Windsor中,接口ILifecycleConcern提供特定的组件生命周期管理:
public interface ILifecycleConcern { void Apply( ComponentModel model, object component ); }
  现在我们要实现组件的自动创建和销毁,就需要实现接口ILifecycleConcern,在Startable Facility中分别用两个类来实现,第一个类StartConcern,它判断如果组件实现了接口IStartable,则直接调用它的Start()方法;如果组件是用特性startMethod,则获取并调用具有startMethod特性的方法:
public class StartConcern : ILifecycleConcern { private static readonly StartConcern _instance = new StartConcern(); protected StartConcern() { } public static StartConcern Instance { get { return _instance; } } public void Apply(ComponentModel model, object component) { if (component is IStartable) { (component as IStartable).Start(); } else if (model.Configuration != null) { String startMethod = model.Configuration.Attributes["startMethod"]; if (startMethod != null) { MethodInfo method = model.Implementation.GetMethod(startMethod); method.Invoke(component, null); } } } }
0
相关文章