是否应该通过DI使用Entity Framework DbContext的存储库实现IDisposable?

时间:2021-08-11 15:40:47

I have seen with examples of EF7 people injecting the datacontext in the constructor.

我已经看到EF7人在构造函数中注入datacontext的例子。

However, since DbContext implements IDisposable I fear that my repositories would also have to implement IDisposable, propagating through the code.

但是,由于DbContext实现了IDisposable,我担心我的存储库也必须实现IDisposable,通过代码传播。

The examples I've seen haven't implemented IDisposable, but I'm not sure why.

我见过的例子没有实现IDisposable,但我不确定为什么。

Edit

To clarify previously I was using the db context in the usual manner

为了澄清之前我以通常的方式使用db上下文

using(var db = new SomeContext())
{
    return await from row in db.Table
        select row).ToListAsync();
}

Looking at the injection way of doing things the DbContext would be passed into the repository constructor, but would this repository have to implement IDisposable to dispose of the DbContext once Repository is done with?

看看注入的处理方式,DbContext将被传递到存储库构造函数中,但是一旦存储库完成,这个存储库是否必须实现IDisposable来处理DbContext?

Is there a risk with this DBContext hanging around if the Repository subsequently calls another repository class that changes its injected DbContext?

如果存储库随后调用另一个更改其注入的DbContext的存储库类,那么这个DBContext是否存在风险?

i.e

public SomeOtherRepository (SomeContext db)
{
    this.db = db;
}

*

public SomeRepository (SomeOtherRepository repo, SomeContext db)
{
    this.repo = repo;
    this.db = db;
}
public async TaskAdd(Row row)
{
    db.Some.Add(row);
    await db.SaveChangesAsync();
    repo.AddSomethingElse(row.Id);
}

1 个解决方案

#1


You are not required to override DbContext.Dispose.

您不需要覆盖DbContext.Dispose。

Unless you need to deallocate resources created in your customizations of DbContext, the base implementation the framework provides should be sufficient.

除非您需要释放在DbContext自定义中创建的资源,否则框架提供的基本实现应该足够了。

#1


You are not required to override DbContext.Dispose.

您不需要覆盖DbContext.Dispose。

Unless you need to deallocate resources created in your customizations of DbContext, the base implementation the framework provides should be sufficient.

除非您需要释放在DbContext自定义中创建的资源,否则框架提供的基本实现应该足够了。