DI与一次性物品 [英] DI with disposable objects

查看:126
本文介绍了DI与一次性物品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的存储库类看起来像这样:

  class myRepository:IDisposable {
private DataContext _context;
public myRepository(DataContext context){
_context = context;
}
public void Dispose(){
//执行:实现处理DataContext
}
}
/ pre>

现在,我正在使用Unity控制我的存储库和数据上下文将生命周期配置为:

DataContext - 单例

myRepository 每次创建一个新的实例



这是否意味着我不应该在存储库中实现IDisposable来清理DataContext?



有关这些项目的任何指导?



编辑:
DataContext - singleton - 作为一般规则,抽象依赖关系

解决方案

不应该从IDisposable 派生,因为它将是一个泄漏抽象。依赖关系可能或可能不具有依赖于具体实现的非托管资源。在任何情况下,容器应该管理生命周期,所以消费者不应该这样做 - 它不知道依赖的生命周期:它可以与其他消费者共享,在这种情况下



那就是说,一个(LINQ to SQL?)DataContext代表了一个不同的问题,因为它已经是实现IDisposable,并且你不能很好地改变它,因为它在BCL中定义。



你可以正确地实现IDisposable为你的存储库,但这意味着你会必须对所有存储库和数据文本匹配生命周期



另一个选择是简单地忽略您所持有的一次性资源,但是如果你这样做,你必须使绝对肯定,Unity在适当的时候正确处理DataContext - 但是由于你计划使用Singleton lifet ime,这不应该是一个问题。


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

解决方案

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.

这篇关于DI与一次性物品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆