Windsor Container: How to force dispose of an object?

后端 未结 3 2036
别跟我提以往
别跟我提以往 2021-02-08 03:15

I have an object that implements IDisposable that is registered with the Windsor Container and I would like to dispose of it so it\'s Dispose method is called and next time Reso

3条回答
  •  悲&欢浪女
    2021-02-08 03:57

    Alright, so I've been running tests and it seems like Container.Release() WILL implicitly cause an IDisposable's Dispose() method to execute only if the lifestyle is Transient (this is probably not exactly correct but point is that it wont' do a darn thing if the lifestyle is singleton).

    Now if you call Container.Dispose() it WILL call the disposable methods also, though unfortunately it will dispose of the whole kernel and you will have to add all components back in:

    var container = new WindsorContainer();
    container.AddComponentWithLifestyle(Castle.Core.LifestyleType.Singleton);
    var obj = container.Resolve();  // Create a new instance of MyDisposable
    obj.DoSomething();
    var obj2 = container.Resolve();  // Returns the same instance as obj
    obj2.DoSomething();
    container.Dispose();  // Will call the Disposable method of obj
    // Now the components need to be added back in   
     container.AddComponentWithLifestyle(Castle.Core.LifestyleType.Singleton);
    var obj3 = container.Resolve();  // Create a new instance of MyDisposable
    

    Fortunately in my case I can afford to just drop all components and I can restore them fairly easily. However this is sub-optimal.

提交回复
热议问题