【问题标题】:UoW & Repository + Service LayerUoW & 存储库 + 服务层
【发布时间】:2011-03-19 21:06:52
【问题描述】:

我正在使用以下 T4 创建我的存储库和 UoW: http://blogs.microsoft.co.il/blogs/gilf/archive/2010/07/05/repository-and-unit-of-work-t4-template-for-entity-framework.aspx

现在我正在尝试添加一个服务层。我能够完成这样的事情:

public ActionResult Index()
{
    using (DataEntities context = new DataEntities())
    {
        UnitOfWork uow = new UnitOfWork(context);

        //Service
        ClientService cli = new ClientService(uow);
        var col = cli.getActive();

        //Map results to ViewModel
        var list = AutoMapper.Mapper.Map<IEnumerable<Client>, IEnumerable<ClientListViewModel>>(col);

        return View(list);
    }
}

这很好用,但是...

将 UoW 实例传递给服务层在架构上是否正确?
(我在其 ctor 中使用 IUnitOfWork)

我尝试在服务层内移动上下文和 UoW,但是当我尝试将结果映射到控制器中的 ViewModel 时,上下文不可用。

谢谢!

【问题讨论】:

    标签: asp.net-mvc service layer unit-of-work


    【解决方案1】:

    我认为不,它不是。再说一次,我不是工作单元的忠实粉丝——我觉得它知道的太多了。我会将必要的存储库传递给您创建的服务。通常,我最终会得到特殊的“GetService”或“CreateService”,但这可能对你有用......(我正在写这个,所以它可能无法构建)

    Public class DoSomethingCoolService : IDoSomethingCoolService
    {
    
         private IRepository<SomethingINeed> _neededRepository;
    
         public DoSomethingCoolService(connectionOrContext)
         {
              //setup
         }
    
         public DoSomethingCoolService(IRepository<SomethingINeed> neededRepository)
         {
              _neededRepository = neededRepository;
         }
    
         public List<SomethingINeed> ReturnWhatIWant()
         {
              _neededRepository.Where(x => x.WhatIWant = true);
         }
    
    }
    

    就我个人而言,我不喜欢这样。我更喜欢这样的东西......

    public interface IGetService<T>
    {
        //usual get suspects here
    }
    
    public class GetService<T> : IGetService<T>
    {
        private IRepository<T> _repository;
        GetService(IRepository<T> repository)
    
        //use repository to call gets
    }
    

    现在是复杂的东西......

    public interface IGetClientService : IGetService<Client>
    {
         List<Client> GetClientsForSomething(int someId);
    }
    
    public class GetClientService : GetService<Client>, IGetClientService
    {
            private IRepository<Client> _repository;
            GetClientService(IRepository<Client> repository) : base(repository)
    
            public List<Client> GetClientsForSomething(int someId)
            {
                  //some crazy cool business logic stuff here you want to test!
            }
    }
    

    然后在我的控制器中,我只是依赖于 IGetClientService,并在必要时使用它。易于测试,易于制作不依赖它的另一个。

    这有意义吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 2011-05-21
      • 1970-01-01
      • 2016-02-05
      • 2011-03-03
      • 1970-01-01
      相关资源
      最近更新 更多