EF - 和存储库模式 - 多个上下文 [英] EF - and repository pattern - multiple contexts

查看:151
本文介绍了EF - 和存储库模式 - 多个上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.MVC2中的EF中面临一些上下文的麻烦。



我认为在DataBase中改进一些操作的最佳方法是创建了Repository。我的repo类添加,删除,选择很多项目,所以我不需要写

 (使用< name> Context =新(...等)){...} 

存储库消除了初始化上下文每个操作,但不要处理上下文。



什么是管理上下文的最佳方法?如果我创建其他存储库类,并尝试执行任何需要两个上下文中的对象的操作,都会出现问题。



是否有任何其他方式或更好的方式来实现存储库,管理上下文?任何有趣的模式?

解决方案

上下文是一个工作单位,所以每个Web请求都需要一个。



因此,您应该使用构造函数注入(即构造函数参数)为所有存储库提供单个上下文,并在请求结束时处理它。



大多数DI框架都会自动执行。


I've faced some troubles with context in EF in ASP.MVC2.

I thought that best way to improve some operation on DataBase i've created Repository. My repo class adds, deletes, select many items so i don't need to write

(using <name>Context = new (... etc ...) ) { ... }

Repository eliminates initializing context for every operation, but don't dispose the context.

What is the best way to manage contexts? If i create other repository class and try to do any operation which will need objects from both contexts there is a problem.

Is there any other way or better way to implement repository, to manage contexts? Any interesting pattern?

解决方案

A context is a unit of work, so you want one per web request.

Therefore, you should use constructor injection (i.e., a constructor argument) to supply a single context for all repositories, and dispose it at the end of the request.

Most DI frameworks will do this automatically.

这篇关于EF - 和存储库模式 - 多个上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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