我应该在哪里在MVC应用程序创建我的实体框架上下文对象? [英] Where should I create my Entity Framework context object in an MVC app?

查看:124
本文介绍了我应该在哪里在MVC应用程序创建我的实体框架上下文对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用session-per-request模式,如在ASP.NET环境中使用NHibernate时频繁。

我首先想到的是把code创建在Global.asax中BeginRequest事件处理程序的背景下,但我发现这个事件不仅对实际执行工作的初始请求开火,而且还对静态文件,如CSS和图像的后续请求。

我不希望创建一大堆不是在需要时额外的环境中,那么有没有一种方法,我可以只让我的code对初始请求运行,而不是那些为静态文件?


解决方案

  1. 使用构造函数注入任何东西,需要一个上下文。

  2. 使用您所选择的DI框架和地图的背景。

  3. 范围的上下文请求范围。

I would like to use the Session-per-request pattern, as is done frequently when using NHibernate in an ASP.NET environment.

My first thought was to put the code to create the context in the BeginRequest event handler in Global.asax, but I discovered that this event is firing not only for the initial request that actually does the work, but also for the subsequent requests for static files such as CSS and images.

I don't want to create a whole bunch of extra contexts when they're not needed, so is there a way I can just get my code to run on the initial request, and not the ones for the static files?

解决方案

  1. Use constructor injection for anything which needs a context.
  2. Use the DI framework of your choice and map the context.
  3. Scope the context as request-scoped.

这篇关于我应该在哪里在MVC应用程序创建我的实体框架上下文对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆