MVC 3 EF 4.1
我选择两种方法来处理DbContext:
>在Application_BeginRequest中实例化,放入
HttpContext.Current.Items并在Application_EndRequest中进行处理。
>创建一次性UnitOfWork(kindof wrapper for DbContext)和
使用(var unitOfWork = new)启动每个控制器操作
UnitOfWork()){…}
解决方法
我建议你使用依赖注入框架。您可以根据请求注册您的DbContext
container.RegisterType<MyDbContext>().InstancePerHttpRequest();
并将其作为构造函数参数注入到控制器。
public class MyController : Controller { public MyController(MyDbContext myDbContext) { _myDbContext = myDbContext; } }
如果注册类型实现Idisposable,那么DI框架将在请求结束时处理它。
第一种方法:使用ID框架比手动实现它要清楚得多。此外,您的所有请求可能不需要您的UoW。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。