简体   繁体   中英

One object per HttpContext instance

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.

- makes db requests -发出数据库请求

- abstracting the underlying db model -抽象底层数据库模型

- All business logic happenes here. -所有业务逻辑都在这里发生。

- 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)?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM