代码之家  ›  专栏  ›  技术社区  ›  ruslander

Castle Windsor,Hook Continer Release,以便调用显式组件释放

  •  1
  • ruslander  · 技术社区  · 15 年前

    我在应用程序启动时运行这个

    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 回复  |  直到 15 年前
        1
  •  2
  •   Mauricio Scheffer    15 年前

    您可以使用 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);}
            }
        }
    }
    

    当然,静态数组列表只用于演示目的。