2

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.

  1. Is there a better way to couple the lifetime of the object with the HttpContext?
  2. Is it possible to do it using Unity (DI/IoC framework)?
Oybek
  • 7,016
  • 5
  • 29
  • 49
  • Why you don't use a member variable to store che DbContext instead of using the HttpContext.Items dictionary? – Marco Staffoli Dec 03 '11 at 00:31
  • @Bugeo Can you be more specific and support it with code snippet? – Oybek Dec 03 '11 at 04:51
  • https://github.com/ayende/TekPub.Profiler.BackOffice/blob/master/TekPub.Profiler.BackOffice/Controllers/RavenController.cs – Marco Staffoli Dec 03 '11 at 09:04
  • @Bugeo Thank you but, in my case this is not suitable because in my application there are cases where several actions from different controllers are executed (via `Html.RenderAction()`) – Oybek Dec 03 '11 at 10:12

1 Answers1

1

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

np-hard
  • 5,725
  • 6
  • 52
  • 76
  • Thank you for your link. Most likely I'll check out the `PerThreadLifetimeManager`. Most likely it will satisfy my requirements as all DB queries will be made in one thread. – Oybek Dec 02 '11 at 23:12