I'm currently writing a project in ASP.NET MVC. I have a web project and DB project which solely works with DB. The layers look like this and they interoperate only with sibling layers.
DB project (EF CF) - makes db requests
Repository - abstracting the underlying db model
Service - All business logic happenes here.
ASP.NET MVC Web application - Front end presentation
They must be loosely coupled so I'm using Unity DI/IoC framework
What I want to achieve is to create one instance of DbContext
per http request. The following is the logic I implemented so far.
public class MyAppBaseController : Controller {
protected override void OnActionExecuting(ActionExecutingContext filterContext) {
if (HttpContext.Items["DbModel"] == null) {
HttpContext.Items["DbModel"] = MySingleton.Container.Resolve<DbContext>();
}
base.OnActionExecuting(filterContext);
}
}
What is does is that in request pipeline if the Items
dictionary of the current HttpContext
doesn't have DbContext
, it adds one. All controllers inherit from it. The reason why I'm doing so is that all repositories that will be called during execution should use exactly the same DbContext
object for all sequential db calls.
HttpContext
?you can take control over the instance lifetime of your dependencies in unity's object lifetime management as specified here
you will have to write your own that injects your object instance in httpcontext