I am developing an application and I started to use as my base some code from an example by John Papa. Looking on the web I found this same code and it appears in an answer to a
OK. Here's my best shot:
The point of keeping repositories in a cache is to ensure that the repository is only initiated once per request. The repository cache is in the RepositoryProvider
class and is exposed to the UnitOfWork
by the GetRepositoryForEntityType
method. So the advantage is that the unit of work is not concerned with caching or creation of repositories.
The RepositoryProvider
class is instantiated once per unit of work. (NB - it is desirable to create the repositories new for every request). The RepositoryProvider
keeps the repositories in a dictionary using the type as a key. This is fine when using the generic repository base which has a Type
parameter. But what if you have created a custom repository? In this example the creation of repositories by type is handed off to the RepositoryFactories
class via the MakeRepository
method. The advantage is that creating repositories is separated from caching.
The RepositoryFactories
class knows when to make a custom repository because it contains a dictionary that uses Type as a key and a function as a value. The function is the constructor for a custom repository. If there's a value in the dictionary then use that constructor otherwise just use the generic base constructor.
All this means that as you add entities you do not have to modify any of these classes unless you create a custom repository. And when you do that all you have to do is add an entry to the dictionary in RepositoryFactories