Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
924 views
in Technique[技术] by (71.8m points)

entity framework - EF4: ObjectContext Lifetime?

I am developing a WPF desktop app that uses Entity Framework 4 and SQL Compact 4. I have seen two distinct styles of Repository classes:

  • The Repository instantiates an ObjectContext, which is disposed of when the Repository is garbage-collected. The lifetime of the ObjectContext is the same as the lifetime of the application.

  • A separate DataStoreManager class creates and holds an ObjectContext for the life of the application. When a repository is needed, a command gets an ObjectContext reference from the DataStoreManager and passes it to the constructor for the New Repository. The lifetime of the ObjectContext is the lifetime of the application.

Is either approach considered a bad practice? Does either present any absolute advantages over the other? Is either approach considered best practice? Is either more widely accepted or used by developers than the other? Thanks for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The best practice is depended on how your users are going to use the application: And how your application is structured.

if there is only one user using your application at one time, you can even create your entity context as a static instance.

context can be used per request, per thread, per form.

read more: http://blogs.microsoft.co.il/blogs/gilf/archive/2010/02/07/entity-framework-context-lifetime-best-practices.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...