public interface IStartable
{
void Start();
void Stop();
}
Windsor 中 ILifecycleConcern 提供特定生命週期管理:
public interface ILifecycleConcern
{
void Apply(ComponentModel model, object component);
}
public class StartConcern : ILifecycleConcern
{
private static readonly StartConcern _instance = new 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)
model.Implementation.GetMethod(startMethod).Invoke(component, null);
}
}
}
public class StopConcern : ILifecycleConcern
{
private static readonly StopConcern _instance = new StopConcern();
public static StopConcern Instance { get { return _instance; } }
public void Apply(ComponentModel model, object component)
{
if (component is IStartable)
(component as IStartable).Stop();
else if (model.Configuration != null)
{
string stopMethod = model.Configuration.Attributes["stopMethod"];
if (stopMethod != null)
model.Implementation.GetMethod(stopMethod).Invoke(component, null);
}
}
}
繼承 AbstractFacility,實作 IFacility:
public interface IFacility
{
void Init(IKernel kernel, IConfiguration facilityConfig);
void Terminate();
}
protected override void Init()
{
converter = (ITypeConverter)Kernel.GetSubSystem(SubSystemConstants.ConversionManagerKey);
Kernel.ComponentModelCreated += new ComponentModelDelegate(OnComponentModelCreated);
Kernel.ComponentRegistered += new ComponentDataDelegate(OnComponentRegistered);
}
private void OnComponentRegistered(string key, IHandler handler)
{
bool startable = (bool)handler.ComponentModel.ExtendedProperties["startable"];
if (startable)
{
if (handler.CurrentState == HandlerState.WaitingDependency)
waitList.Add(handler);
else
Start(key);
}
CheckWaitingList();
}
private void CheckWaitingList()
{
IHandler[] handlers = (IHandler[])waitList.ToArray(typeof(IHandler));
IList validList = new ArrayList();
foreach (IHandler handler in handlers)
if (handler.CurrentState == HandlerState.Valid)
{
validList.Add(handler);
waitList.Remove(handler);
}
foreach (IHandler handler in validList)
Start(handler.ComponentModel.Name);
}
private void Start(string key)
{
object instance = Kernel[key]; // 觸發 ComponentModelCreated
}
private void OnComponentModelCreated(ComponentModel model)
{
bool startable = CheckIfComponentImplementsIStartable(model) || HasStartableAttributeSet(model);
model.ExtendedProperties["startable"] = startable;
if (startable)
{
model.LifecycleSteps.Add(LifecycleStepType.Commission, StartConcern.Instance);
model.LifecycleSteps.Add(LifecycleStepType.Decommission, StopConcern.Instance);
}
}
流程總結:組件註冊 → 檢查依賴 → 不滿足加入等待列表 → 滿足則 Start → 觸發建立實例 → OnComponentModelCreated 註冊 StartConcern/StopConcern → 進入 Commission 階段執行 Start() → 容器釋放時執行 Stop()。完整實現組件依賴就緒自動啟動與銷毀。