开发者

UoW & Repository + Service Layer

I'm using the following T4 to create my Repository & UoW: http://blogs.microsoft.co.il/blogs/gilf/archive/2010/07/05/repository-and-unit-of-work-t4-template-for-entity-framework.aspx

Now I'm trying to add a Service Layer. I was able to accomplish something like this:

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开发者_C百科<ClientListViewModel>>(col);

        return View(list);
    }
}

This works fine, but...

Is architecturally correct to pass the UoW instance to the Service Layer?

(I'm using IUnitOfWork in its ctor)

I tried to move the context & UoW inside the service layer, but the context is not available when I try to map the results to ViewModel in the controller.

Thanks!


I would argue no it isn't. Then again, I'm not a huge fan of unit of work -- I feel like it knows too much. I would pass the necessary repository(ies) to the service you create. Typically, I end up with special "GetService" or "CreateService" but this might work for you... (I'm writing this freehand so it might not build)

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);
     }

}

Personally, I don't like this. I prefer something more like this ...

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
}

now for the complicated-ish stuff...

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!
        }
}

Then inside my controller, I just have a dependency on the IGetClientService, and use it where necessary. Easy to test, easy to make another that isn't dependent on it.

Does this make any sense?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜