Unit Of Work & Generic Repository with Entity Framework 5

后端 未结 2 1863
孤城傲影
孤城傲影 2020-12-12 14:09

I\'m using ASP.NET MVC 4 with Entity Framework 5. I have model classes and Entity Maps to map existing tables to those model classes. All this is setup fine and works great.

2条回答
  •  长情又很酷
    2020-12-12 14:40

    Your ExampleService class is expecting IUnitOfWork, that means you just need another IUnitOfWork that is a Mock and its GetRepository() method will return an IRepository Mock.

    For example (not really a Mock but In-Memory stub):

      public InMemoryRepository : IRepository where T : class
      {
            ........
      }
    
      public InMemoryUnitOfWork : IUnitOfWork
      {
           public IRepository GetRepository() where TEntity : class
           {
                return new InMemoryRepository();
           }
      }
    

    Then:

    public IEnumerable GetAll()
    {
        // Create Unit Of Work object
        IUnitOfWork uow = new InMemoryUnitOfWork();
    
        // Create Service with Unit Of Work
        ExampleService service = new ExampleService(uow);
    
        return service.getAll();
    }
    

提交回复
热议问题