entity framework - C#/EF and the Repository Pattern: Where to put the ObjectContext in a solution with multiple repositories? -
i have multiple repositories in application. should put objectcontext? right now, have reference objectcontext ctx;
in every repository. smartest , safest way go this?
a design multiple objectcontext
instances acceptable if repository
methods commit transaction. otherwise, possible external calls commit transaction may not persist intend, because hold references different instances of objectcontext
.
if want restrict objectcontext
single instance, can build repositoryprovider
class contains objectcontext
, , manages propagation of repository actions data commits. can best accomplished either, - injecting objectcontext
reference each repository, or - subscribing repositories' events eventhandler
s call appropriate methods on objectcontext
.
the following highly pluggable implementation have used:
repository provider interface
public interface irepositoryprovider { irepository this[type repositorytype] { get; } }
repository factory interface
the implementation has dependency on ienumerable<ifilteredrepositoryfactory>
.
public interface ifilteredrepositoryfactory{ bool cancreaterepository(type repositorytype); irepository createrepository(type repositorytype, objectcontext context); }
so, implementation looks like:
repository provider class
public class repositoryprovider { public repositoryprovider(objectcontext context, ienumerable<ifilteredrepositoryfactory> repositoryfactories) { _context = context; _repositoryfactories = repositoryfactories; } private readonly objectcontext _context; private readonly ienumerable<ifilteredrepositoryfactory> _repositoryfactories; private readonly dictionary<type, irepository> _loadedrepositories; irepository this[type repositorytype] { { if(_loadedrepositories.containskey(repositorytype)) { return _loadedrepositories[repositorytype]; } var repository = getfactory(repositorytype).createrepository(repositorytype, _context); _loadedrepositories.add(repositorytype,repository); return repository; } } ifilteredrepositoryfactory getfactory(type repositorytype) { //throws exception if no repository factory found return _repositoryfactories.first(x => x.cancreaterepository(repositorytype)); } }
it should noted new repository
created first matching factory implementation. so, if collection of factories contains multiple factories can create repository
given repository type
, first ifilteredrepositoryfactory
object in enumerable used , subsequent factories ignored. in addition, if there no registered factory, , exception thrown.
Comments
Post a Comment