DI with disposable objects

前端 未结 3 1319
庸人自扰
庸人自扰 2021-01-21 09:57

Suppose my repository class looks like this:

class myRepository : IDisposable{
    private DataContext _context;
    public myRepository(DataContext context){
           


        
3条回答
  •  一向
    一向 (楼主)
    2021-01-21 10:27

    As a general rule, abstract dependencies should not derive from IDisposable, because it would be a Leaky Abstraction. A dependency may or may not hold unmanaged resources dependending on concrete implementation. In any case, the container should manage lifetime, so it's not up to the consumer to do so - it has no knowledge of the lifetime of the dependency: it could be shared with other consumers, in which case it would be destructive to prematurely dispose of it.

    That said, a (LINQ to SQL?) DataContext represents a different problem because it already implements IDisposable, and you can't very well change this because it's defined in the BCL.

    You can either properly implement IDisposable for your repository, but that means that you will have to match lifetime for all repositories and the datacontext.

    The other alternative is to simply ignore that you are holding on to a disposable resource, but if you do that, you will have to make absolutely sure that Unity properly disposes of the DataContext at the appropriate time - but since you plan on using the Singleton lifetime, this shouldn't be a problem.

提交回复
热议问题