Main content
Principle Analysis of startable facility
......
In the Castle IOC container practice startable Facility (a) we have seen how to use startable facility, this article will do some analysis of its principles. First look at the interface istartable, its implementation code is as follows:
public interface IStartable
{
void Start();
void Stop();
}
The code is fairly simple, with only two methods that are executed when the component is created and when it is destroyed, which involves the lifecycle management of the component. In Windsor, interface Ilifecycleconcern provides specific component lifecycle management:
public interface ILifecycleConcern
{
void Apply( ComponentModel model, object component );
}
Now we want to implement the automatic creation and destruction of components, we need to implement the interface Ilifecycleconcern, in the startable facility, respectively, two classes to implement, the first class Startconcern, It determines if the component implements the interface istartable, it calls its start () method directly, or if the component is using an attributestartMethod,则获取并调用具有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);
}
}
}
}