Just wondering, in an ASP.NET MVC3 environnement with entity framework. Should the Unit of Work point to the service layer or the repository (and then the repository point to the service layer) ?
Ive saw two example:
Link: Entity Framework 4 CTP 4 / CTP 5 Generic Repository Pattern and Unit Testable
Doesn't use a service layer but its obvious that one could be use in that case.
Link: http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit- of-work-patterns-with-entity-framework-4-0.aspx
What would be better ?
Thanks.
Well actually, if you think about it, the Controllers should work with the Unit of Work.
Typically in an ASP.NET MVC application, a Controller is assigned a new unit of work when a HTTP Request comes in.
The Controller will then call methods on the service (which calls methods on the Repository), fetching and making changes to the Entity Framework internal graph/memory.
Once the Controller has done what it needs to do, it will perform a "Commit" on the Unit of Work, which results in any changes to the underlying repository being commited to the database.
I assume when you talk about a "Service", you have a intermediary layer between your Controller and Repository, where the Controller only talks to the Service, the Service then talks to the Repository, then back up the app stack.
So your Controller might look like this:
public class ProductsController : Controller
{
private IUnitOfWork _unitOfWork;
private IProductsService _service;
public ProductsController(IUnitOfWork unitOfWork, IProductsService service)
{
// use dependency injection here
_unitOfWork = unitOfWork;
_service = service;
}
[HttpPost]
public ActionResult SubmitOrder(Product p)
{
var existingProduct = _service.FindById(p.ProductId);
UpdateModel(existingProduct);
_unitOfWork.Commit();
}
}
In most EF4 scenarios, the Unit of Work is implemented as a wrapper for the ObjectContext. In other words, the "Commit" method on your Unit of Work would simply perform "SaveChanges" on the ObjectContext.
Therefore, the Unit of Work doesn't really point to either the service or the repository. It simply works with the persistence mechanism that is manages.
I'm not sure what you mean by "point to", but I think transactions are the responsibility of the service layer, not persistence.
A persistence object can't know if it's part of a larger unit of work. The responsible service has references to all the model and persistence objects that make up the unit of work. The service is responsible for managing connections from the pool on behalf of the persistence objects as well. Obtain the connection, open the transaction, perform the work, either commit or rollback the transaction, and close the connection. That's the service's job.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With