DI with disposable objects

纵饮孤独 提交于 2019-12-20 03:15:13

问题


Suppose my repository class looks like this:

class myRepository : IDisposable{
    private DataContext _context;
    public myRepository(DataContext context){
        _context = context;
    }
    public void Dispose(){ 
        // to do: implement dispose of DataContext
    }
}

now, I am using Unity to control the lifetime of my repository & the data context & configured the lifetimes as:
DataContext - singleton
myRepository - create a new instance each time

Does this mean that I should not be implementing the IDisposable on the repository to clean up the DataContext?

Any guidance on such items?

EDIT: DataContext - singleton - read this as singleton per-web request


回答1:


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.




回答2:


If I were you, I would either do a UnitOfWork pattern implementation instead, or let the IOC container manage the lifetime of your DataContext.

Structuremap for instance has a HttpContextScoped option, so that you register your DataContext like so:

For<DataContext>().HttpContextScoped().Use<MyDataContext>();



回答3:


Does this mean that I should not be implementing the IDisposable on the repository to clean up the DataContext?

It sounds like it - from what you're saying, all repositories will share the same DataContext, but the first repository you create will dispose of it.

What creates the DataContext? Whatever that is, it should dispose of it.



来源:https://stackoverflow.com/questions/2404007/di-with-disposable-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!