I've been trying to implement a .NET MVC Unit of Work API (rather than creating a separate repository), but it doesn't feel right. Am I going about this the correct way?
Following advice from here.
BaseController
public class BaseController : ApiController
{
protected DBEntities _dbEntities;
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
_dbEntities = new DBEntities();
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
_dbEntities.SaveChanges();
}
}
MyController
public class MyController : BaseController
{
public HttpResponseMessage PutMyObject(int id, int id2)
{
if (id != 0)
{
var myObject = _dbEntities.MyObjects.Where(x => x.id == id);
if (myObject.Count() > 0)
{
MyObject temp = myObject.SingleOrDefault();
temp.Processed = true;
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound);
}
}
else
{
/* do some other stuff */
}
}
}
My thinking around this is that the controller action is a single Unit of Work. The database connection is opened when the controller action starts, and SaveChanges is called once the response is returned.
Am I going about this in the correct manner? Do I need to dispose of _dbentities
after SaveChanges
is called within the BaseController
?
1 Answer 1
I can be very short about this:
- Single responsibility: a controller shouldn't also have Unit of Work responsibilities. The context itself is the perfect Unit of Work.
- You don't always need
SaveChanges
- Use dependency injection.
I like to see controllers as light-weight doorways to web-independent service methods. The services have their own DbContext
and execute SaveChanges
where necessary and, thus, can be used in other applications than just MVC/Web API applications. Controllers receive services by dependency injection.