[英]One object per HttpContext instance
I'm currently writing a project in ASP.NET MVC. 我目前正在用ASP.NET MVC编写一个项目。 I have a web project and DB project which solely works with DB. 我有一个仅与DB一起使用的Web项目和DB项目。 The layers look like this and they interoperate only with sibling layers. 这些层看起来像这样,它们只能与同级层进行互操作。
DB project (EF CF) - makes db requests 数据库项目(EF CF) -发出数据库请求
Repository - abstracting the underlying db model 存储库 -抽象底层数据库模型
Service - All business logic happenes here. 服务 -所有业务逻辑都在这里发生。
ASP.NET MVC Web application - Front end presentation ASP.NET MVC Web应用程序 -前端演示
They must be loosely coupled so I'm using Unity DI/IoC framework 它们必须松散耦合,所以我正在使用Unity DI / IoC框架
What I want to achieve is to create one instance of DbContext
per http request. 我要实现的是为每个http请求创建一个DbContext
实例。 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. 它的作用是在请求管道中,如果当前HttpContext
的Items
字典没有DbContext
,它将添加一个。 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. 我这样做的原因是,在执行过程中将被调用的所有存储库应该对所有顺序的db调用使用完全相同的DbContext
对象。
HttpContext
? 有没有更好的方法将对象的生存期与HttpContext
耦合在一起?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.