AbstractComponentActivator
Abstract implementation of IComponentActivator. The implementors must only override the InternalCreate and InternalDestroy methods in order to perform their creation and destruction
logic.
using Castle.Core;
using Castle.DynamicProxy;
using Castle.MicroKernel.Context;
using System;
using System.Collections.Generic;
namespace Castle.MicroKernel.ComponentActivator
{
[Serializable]
public abstract class AbstractComponentActivator : IComponentActivator
{
private readonly IKernelInternal kernel;
private readonly ComponentModel model;
private readonly ComponentInstanceDelegate onCreation;
private readonly ComponentInstanceDelegate onDestruction;
public IKernelInternal Kernel => kernel;
public ComponentModel Model => model;
public ComponentInstanceDelegate OnCreation => onCreation;
public ComponentInstanceDelegate OnDestruction => onDestruction;
protected AbstractComponentActivator(ComponentModel model, IKernelInternal kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
{
this.model = model;
this.kernel = kernel;
this.onCreation = onCreation;
this.onDestruction = onDestruction;
}
protected abstract object InternalCreate(CreationContext context);
protected abstract void InternalDestroy(object instance);
public virtual object Create(CreationContext context, Burden burden)
{
object obj = InternalCreate(context);
burden.SetRootInstance(obj);
onCreation(model, obj);
return obj;
}
public virtual void Destroy(object instance)
{
InternalDestroy(instance);
onDestruction(model, instance);
}
protected virtual void ApplyCommissionConcerns(object instance)
{
if (Model.Lifecycle.HasCommissionConcerns) {
instance = ProxyUtil.GetUnproxiedInstance(instance);
if (instance == null)
throw new NotSupportedException($"""{Model.Name}""");
ApplyConcerns(Model.Lifecycle.CommissionConcerns, instance);
}
}
protected virtual void ApplyConcerns(IEnumerable<ICommissionConcern> steps, object instance)
{
foreach (ICommissionConcern step in steps) {
step.Apply(Model, instance);
}
}
protected virtual void ApplyConcerns(IEnumerable<IDecommissionConcern> steps, object instance)
{
foreach (IDecommissionConcern step in steps) {
step.Apply(Model, instance);
}
}
protected virtual void ApplyDecommissionConcerns(object instance)
{
if (Model.Lifecycle.HasDecommissionConcerns) {
instance = ProxyUtil.GetUnproxiedInstance(instance);
ApplyConcerns(Model.Lifecycle.DecommissionConcerns, instance);
}
}
}
}