IOC containers and IDisposable

后端 未结 1 824
攒了一身酷
攒了一身酷 2020-12-10 05:22

It was recommended to me that, when using an IOC container, I should change this:

class Foobar: IFoobar, IDisposable {};

Into this:

相关标签:
1条回答
  • 2020-12-10 06:12

    Deriving an interface from IDisposable is in my opinion a design smell that indicates a Leaky Abstraction. As Nicholas Blumhardt put it:

    an interface [...] generally shouldn't be disposable. There's no way for the one defining an interface to foresee all possible implementations of it - you can always come up with a disposable implementation of practically any interface.

    Consider why you want to add IDisposable to your interface. It's probably because you have a particular implementation in mind. Hence, the implementation leaks into the abstraction.

    An DI Container worth its salt should know when it creates an instance of a disposable type. When you subsequently ask the container to release an object graph, it should automatically dispose the disposable components (if their time is up according to their lifestyles).

    I know that at least Castle Windsor and Autofac does this.

    So in your case, you should keep your type like this:

    class Foobar: IFoobar, IDisposable {};
    

    You may find Nicholas Blumhardt's post The Relationship Zoo interesting as well - particularly the discussion about Owned<T>.

    0 讨论(0)
提交回复
热议问题