Where should i use the unit of work ? and why?

3.4k views Asked by At

I would want to know where should i use the unit of work ? and why ?

  • Repository level ? But what if you need 2 repositories ?
  • Service level ? But what if you need to reuse other service methods ?
  • Controller level ? But what if you doesnt want to put any logic in your controller ?

Would like to know where its best seen and should be used. I am using an implementation like :

using (var uow = UnitOfWorkFactory.Create())
{
... transaction go here
}

(I am using ASP.NET MVC 3 with Entity Framework)

Thanks.

1

There are 1 answers

2
Greg Buehler On BEST ANSWER

A unit of work lets you perform multiple actions within multiple repositories and call Save() for all of them at once, which calls SaveChanges() which will turn the unit of work into a transaction. If anything fails during your Save() call, the operation is rolled back.

So use a unit of work anywhere you need to make sure something doesn't corrupt during the data transaction. Basically use a unit of work when you want to defer transactions until you have finished a set of actions.

This posting is a pretty good overview of how entity framework intends units of work to be used.