Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 597
David Veeneman Avatar asked Mar 24 '11 02:03

David Veeneman


2 Answers

I would have thought that holding an ObjectContext open over multiple accesses would be bad practice. As soon as it becomes corrupted then you would need to recycle in and handle the corruption.

The Repository pattern is more for abstraction of data access but doesn't necessarily map to lifetime of context.

The unit of work pattern is more about encapsulation of one or more database/repository accesses i.e. a use case may have you adding a new Blog and then adding the first default post, this may require calling two repositories, at this point you might want to share the context and encapsulate these two commands in a transaction. Adding a second post might be done hours later and be a new context/unit of work.

DJ is right in mentioning Context lifetimes which you'd set generally at an application level.

like image 115
JTew Avatar answered Sep 30 '22 05:09

JTew


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

like image 22
D.J Avatar answered Sep 30 '22 05:09

D.J