I have multiple repositories in my application. Where should I put the ObjectContext? Right now, I have a reference like ObjectContext ctx; in every repository. What is the smartest and safest way to go about this?
C#/EF and the Repository Pattern: Where to put the ObjectContext in a solution with multiple repositories?
3.4k Views Asked by Olsen At
2
A design with multiple
ObjectContextinstances is only acceptable if yourRepositorymethods commit the transaction. Otherwise, it is possible that external calls to commit the transaction may not persist everything you intend, because you will hold references to different instances of theObjectContext.If you want to restrict the
ObjectContextto a single instance, then you can build aRepositoryProviderclass that contains theObjectContext, and manages the propagation of repository actions to data commits. This can be best accomplished by either, - Injecting theObjectContextreference into each repository, or - Subscribing the repositories' events toEventHandlers that call the appropriate methods on theObjectContext.The following is a highly pluggable implementation that I have used:
Repository Provider Interface
Repository Factory Interface
The implementation has dependency on an
IEnumerable<IFilteredRepositoryFactory>.So, the implementation looks like:
Repository Provider Class
It should be noted that a new
Repositorywill be created by the first matching factory implementation. So, if the collection of factories contains multiple factories that can create aRepositoryfor the given repositoryType, the firstIFilteredRepositoryFactoryobject in the enumerable will be used and any subsequent factories will be ignored. In addition, if there is no registered factory, and exception will be thrown.