<PackageReference Include="Castle.Windsor" Version="2.5.3" />

ComponentLifecycleExtension

using System; using System.Collections.Generic; namespace Castle.MicroKernel.Handlers { public class ComponentLifecycleExtension : IResolveExtension, IReleaseExtension { private IKernel kernel; private IDictionary<object, IList<ComponentReleasingDelegate>> releasingHandlers; private ComponentResolvingDelegate resolvingHandler; public void Intercept(ReleaseInvocation invocation) { if (releasingHandlers != null) { IList<ComponentReleasingDelegate> value; lock (releasingHandlers) { if (releasingHandlers.TryGetValue(invocation.Instance, out value)) releasingHandlers.Remove(invocation.Instance); } if (value != null) { foreach (ComponentReleasingDelegate item in value) { item(kernel); } } } invocation.Proceed(); } public void Init(IKernel kernel, IHandler handler) { this.kernel = kernel; } public void Intercept(ResolveInvocation invocation) { List<ComponentReleasingDelegate> list = null; if (resolvingHandler != null) { Delegate[] invocationList = resolvingHandler.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { ComponentResolvingDelegate componentResolvingDelegate = (ComponentResolvingDelegate)invocationList[i]; ComponentReleasingDelegate componentReleasingDelegate = componentResolvingDelegate(kernel, invocation.Context); if (componentReleasingDelegate != null) { if (list == null) { list = new List<ComponentReleasingDelegate>(); invocation.RequireDecommission(); } list.Add(componentReleasingDelegate); } } } invocation.Proceed(); if (list != null) { lock (resolvingHandler) { if (releasingHandlers == null) releasingHandlers = new Dictionary<object, IList<ComponentReleasingDelegate>>(); if (!releasingHandlers.ContainsKey(invocation.ReturnValue)) releasingHandlers.Add(invocation.ReturnValue, list); } } } public void AddHandler(ComponentResolvingDelegate handler) { if (resolvingHandler == null) resolvingHandler = handler; else resolvingHandler = (ComponentResolvingDelegate)Delegate.Combine(resolvingHandler, handler); } } }