什么是实例化和处置MVC中的DbContext最好的方式? [英] What is the best way to instantiate and dispose DbContext in MVC?
问题描述
MVC 3 + EF 4.1
MVC 3 + EF 4.1
我选择的方法两者处理的DbContext:
I'm choosing between two approaches to deal with DbContext:
- 实例化
的Application_BeginRequest
,把它放入HttpContext.Current.Items
和Application_EndRequest
处理。 - 创建一次性的UnitOfWork(用于kindof包装
的DbContext
)和
开始使用以每个控制器动作(VAR的UnitOfWork =新
的UnitOfWork()){...}
- Instantiate in
Application_BeginRequest
, put it intoHttpContext.Current.Items
and dispose inApplication_EndRequest
. - Create disposable UnitOfWork (kindof wrapper for
DbContext
) and start each controller action withusing(var unitOfWork = new UnitOfWork()) { ... }
与我们分享您的经验,请:哪一个你preFER?有什么优点和缺点每种方法?
Share your experience please: Which one would you prefer? what are pros and cons for each approach?
推荐答案
我会建议你使用依赖注入框架。您可以在注册的DbContext
为每个请求
I would suggest you use a Dependency Injection framework. You can register your DbContext
as per request
container.RegisterType<MyDbContext>().InstancePerHttpRequest();
和注入它作为构造参数到控制器。
And inject it as a constructor parameter to the controller.
public class MyController : Controller
{
public MyController(MyDbContext myDbContext)
{
_myDbContext = myDbContext;
}
}
如果注册类型实现的IDisposable
然后在请求结束时,DI框架将其丢弃。
If the registered type implements IDisposable
then the DI framework will dispose it when the request ends.
1的方法:这是更清洁的使用ID框架比手动实现它。而且所有请求可能不需要你的UOW。
1st approach: It is much more cleaner to use ID framework than manually implementing it. Further all your requests may not need your UoW.
第二做法:控制器不应该知道如何构建你的UOW(的DbContext)。目的是不减小组件之间的耦合。
2nd approach: The controller should not know how to construct your UoW(DbContext). Purpose is not reduce the coupling between components.
这篇关于什么是实例化和处置MVC中的DbContext最好的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!