问题
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 anObjectContext
, which is disposed of when theRepository
is garbage-collected. The lifetime of theObjectContext
is the same as the lifetime of the application.A separate
DataStoreManager
class creates and holds anObjectContext
for the life of the application. When a repository is needed, a command gets anObjectContext
reference from theDataStoreManager
and passes it to the constructor for the New Repository. The lifetime of theObjectContext
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.
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/5414076/ef4-objectcontext-lifetime