是否明智使用相同的DbContext与多个存储库?多个、明智、DbContext

2023-09-04 03:56:37 作者:躲在被窝里偷偷哭

获取与实体框架和库更深,以便能够更好的测试。想知道这是否是明智的,虽然?

Getting deeper with entity framework and repositories in order to enable better testing. Wondering if this is wise though?

public interface IRepository
{
    int SaveChanges();

    void Dispose();
}

using (MyContext context = new MyContext())
{
    TransactionRepository txns = new TransactionRepository(context); // TransactionRepository implement IRepository
    MappingRepository maps = new MappingRepository(context); // MappingRepositoryimplement IRepository

    SomeCommand command = new SomeCommand(txns, maps);
    command.Execute();
}

每个存储库的在逻辑上是不同的,所以理论上可以在不同的数据源。现在,他们使用同一个数据库,但。每个库类实现IRepository和特别的SaveChanges()与我为简便起见,还没有显示出一些查询方法。

Each of the repositories is logically different, so in theory could be in different data sources. For now, they use the same database though. Each of the repository classes implements IRepository, and notably SaveChanges() along with some query methods that I've not shown for brevity.

什么是对使用多个存储库一个好的做法呢?

What's a good practice for utilize multiple repositories?

推荐答案

这真的可以归结为设计决策的一部分。如果您在以下工作模式组,那么每个存储库很可能将有它自己的范围内;主要是因为根据UOW,每个库调用应该创造它的背景下,这样做的工作,然后再处理它的上下文。

This really comes down to design decisions on your part. If you're following Unit Of Work pattern, then each repository is probably going to have it's own context; mainly because according to UoW, each repository call should create it's context, do it's work, and then dispose of it's context.

有其他很好的理由,虽然共用一个方面,它(恕我直言)之一是上下文必须跟踪实体的状态下,如果你得到一个实体,处置的情况下,做出一些修改实体,然后附加到一个新的背景下,这个新的上下文有去访问数据库,因此可以计算出实体的状态。同样,如果您正在使用的实体(发票,和他们所有的InvoiceItems)的曲线图,那么新的上下文必须获取所有实体的图形,以确定他们的状态。

There are other good reasons to share a context though, one of which (IMHO) is that the context has to track the state of an entity, if you're get an entity, dispose the context, make some modifications to the entity, and then attach to a new context this new context has to go hit the database so it can figure out the state of the entity. Likewise if you're working with graphs of entities (Invoices, and all their InvoiceItems), then the new context would have to fetch all the entities in the graph to determine their state.

现在,如果你使用的网页或者你没有或无法保持状态的服务,那么UOW图案之类的暗示,这是一个公认的最佳实践。

Now, if you're working with web pages or services where you are not or cannot maintain a state, then the UoW pattern is sort of implied and it's a generally accepted "good practice".

 
精彩推荐
图片推荐