Castle Windsor,钩子容器释放以便调用显式组件释放

时间:2009-10-06 13:52:54

标签: castle-windsor facilities

我在应用程序启动时运行

public class ConfigurationFacility : AbstractFacility {
    private readonly List<string> configuredComponents = new List<string>();

    protected override void Init() {
        Kernel.ComponentRegistered += OnComponentRegistered;
        // add environment configurators
    }
    private void OnComponentRegistered(string key, IHandler handler) {
        // if the component is a configurator then run conf settings and add it to configuredComponents
    }}

问题:如何勾选拆除并为每个人调用显式释放?

由于

1 个答案:

答案 0 :(得分:2)

您可以使用ComponentDestroyed IKernel事件,也可以在组件中实施IDisposable。这是一个示例代码:

namespace WindsorInitConfig {
    [TestFixture]
    public class ConfigurationFacilityTests {
        [Test]
        public void tt() {
            OneDisposableComponent component = null;
            using (var container = new WindsorContainer()) {
                container.AddFacility<ConfigurationFacility>();
                container.AddComponent<OneDisposableComponent>();
                component = container.Resolve<OneDisposableComponent>();
            }
            Assert.IsTrue(component.Disposed);
            Assert.Contains(component, ConfigurationFacility.DestroyedComponents);
        }

        public class OneDisposableComponent : IDisposable {
            public bool Disposed { get; private set; }

            public void Dispose() {
                Disposed = true;
            }
        }

        public class ConfigurationFacility : AbstractFacility {
            private readonly List<string> configuredComponents = new List<string>();
            public static readonly ArrayList DestroyedComponents = new ArrayList();

            protected override void Init() {
                Kernel.ComponentRegistered += OnComponentRegistered;
                Kernel.ComponentDestroyed += Kernel_ComponentDestroyed;
                // add environment configurators
            }

            private void Kernel_ComponentDestroyed(ComponentModel model, object instance) {
                DestroyedComponents.Add(instance);
                // uninitialization, cleanup
            }

            private void OnComponentRegistered(string key, IHandler handler) {
                // if the component is a configurator then run conf settings and add it to configuredComponents
                configuredComponents.Add(key);}
        }
    }
}

静态ArrayList当然仅用于演示目的。