开发者

EF where to create and dispose a context? In business layer or in the repository?

Is it better to create and dispose a context in the repository class? or is it better to create the context in the service and pass it to each repository through dependency injection?

If it is only created in the repository, the methods cannot do lazy load开发者_JS百科ing (no use returning IQueryable) in the service/business layer.


Most definitally create it outside the repository. If you create it inside the service the code is strongly coupled to the instance type of the context. This means that you cant have one of your repositories without also having EF. what you really want to do is layer your system so that a repository can use EF as the data source or possibly something else (such as an in memory table).

This matters a lot when it comes to unit testing as you dont want to have to instantiate your database in order to run a unit test.

Take a look at http://blog.staticvoid.co.nz/2011/10/staticvoid-repository-pattern-nuget.html which is my take on how a repository should be implemented with EF4, also i've created a nuget package to implement this pattern in such a way that the code to get a nicely decoupled repository system is about 4 lines.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜