Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have recently been using a service layer to abstract away alot of the business logic of my application. However I've come into an issue where I'm not sure what is best practice on doing the actual persist of any changes I may make to my models.

1) Is it best to implement a SaveChanges() on my Service layer and so inject the IUnitOfWork into each one I use.

    public class BaseService : IService
    {
       private readonly IUnitOfWork _unitOfWork;

       protected BaseService(IUnitOfWork unitOfWork)
       {
          _unitOfWork = unitOfWork;
       }

       public void SaveChanges() 
       {  
          _dbContext.SaveChanges();
       }
    }

Hence my controllers would only ever be injected with my various services and I would call SaveChanges on these.

2) Or, is it best to let my controller, or service user contain the IUnitOfWork reference and let it call the save directly.

    public class MyController
    {
       private readonly IUnitOfWork _unitOfWork;
       private readonly IMyService _myService;

       protected MyController(
          IUnitOfWork unitOfWork,
          IMyService myService)
       {
          _unitOfWork = unitOfWork;
          _myService = myService;
       }

       public void MyAction() 
       {
          // do stuff with service layer

          _unitOfWork.SaveChanges();
       } 
    }

Note: I would use a DI framework like Autofac, Ninject, Unity etc to manage the UnitOfWork creation via a InstancePerHttpRequest lifetime.

3) Or could I leverage action filters and persist the changes on ActionExecuted.

    public class UnitOfWorkActionAttribute : ActionFilterAttribute
    {
        public IUnitOfWork UnitOfWork { get; set; }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            UnitOfWork.SaveChangesAsync().WaitAndUnwrapException();
        }
    }
share|improve this question
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.