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

Rya*_*anW 3 .net c# entity-framework repository-pattern

更深入地了解实体框架和存储库,以便更好地进行测试。想知道这是否明智?

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();
}
Run Code Online (Sandbox Code Playgroud)

每个存储库在逻辑上都是不同的,因此理论上可能位于不同的数据源中。目前,他们使用相同的数据库。每个存储库类都实现 IRepository,特别是 SaveChanges() 以及一些查询方法,为了简洁起见,我没有展示这些方法。

使用多个存储库的良好做法是什么?

phi*_*ady 6

+1 大猩猩,取得一些商品积分。我想补充以下想法。

在 web/mvc 场景中,我使用了数十个存储库并将上下文注入到这些存储库中。我使用存储库基类。我还有在构造函数中使用上下文的 UoW 类。工作单元类包含对上下文所有支持的存储库的引用。我还使用有界上下文。以下是 Julie Lerman 关于该主题的博客示例。 http://www.goodreads.com/author/show/1892325.Julia_Lerman/blog

所以,是的,使用多个上下文和多个存储库是非常有意义的。您甚至可能有多个工作单元类,尽管并发使用工作单元类是另一个讨论。

根据要求添加示例代码:此示例是从 LuW 基类继承的几个 LuW 类之一。注入当前状态和要使用的 DBContext。(或默认)存储库是 CORE 项目的接口。LuW 类位于 DAL 项目中。

基本的 LuW 是这样的......

public interface ILuw : ILuwEvent, IDisposable
  {

   IBosCurrentState CurrentState{ get; set; }
   OperationStatus Commit();

   }
Run Code Online (Sandbox Code Playgroud)

Luw 类本身。

namespace XYZ.DAL
{
public class LuwBosMaster : Luw, ILuwBosMaster
{
    public LuwBosMaster(DbContext context, IBosCurrentState currentState)  
    {
       base.Initialise(context,currentState); 
    }
    public LuwBosMaster()
    {

        base.Initialise(GetDefaultContext(), BosGlobal.BGA.IBosCurrentState);
    }
    public static DbContextBosMaster GetDefaultContext()
    {
     return new DbContextBosMaster("BosMaster");
    }

    //MasterUser with own Repository Class
    private IRepositoryMasterUser _repositoryMasterUser;
    public  IRepositoryMasterUser RepMasterUser
    { get { return _repositoryMasterUser ?? (_repositoryMasterUser = new RepositoryMasterUser(Context, CurrentState)); } }

    //20 other repositories declared adn available within this Luw
    // Some repositories might address several tables other single tables only.
    //  The repositories are based on a base class that common generic behavior for each MODEL object
Run Code Online (Sandbox Code Playgroud)

我相信你已经明白了基本的想法......