【问题标题】:Castle Windsor, hook continer release in order to call explicit components releaseCastle Windsor, hook continer release 以调用显式组件发布
【发布时间】:2009-10-06 13:52:53
【问题描述】:

我在应用程序启动时运行它

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
    }}

问题:如何钩子拆卸并为每个调用显式释放?

谢谢

【问题讨论】:

  • 我希望覆盖 dispose 会有所帮助,但事实并非如此 :(
  • 请多解释一下:什么叫“拆除”,你想释放什么以及为什么。
  • 在应用程序启动时,我正在进行环境验证,如果未配置外部硬件连接等配置...我会这样做...当容器(应用程序)停止时我想要取消初始化并进行清理......我知道还有其他方法可以做到这一点,但我想要一些干净简单的东西

标签: castle-windsor facilities


【解决方案1】:

您可以使用IKernelComponentDestroyed 事件,也可以在组件中实现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 仅用于演示目的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    相关资源
    最近更新 更多