StaticVoid Repository Pattern - NuGet
I recently published a NuGet package which contains my version of the repository pattern for EF4.1 so i thought it would be good to write a bit of an explanation of how i use it and what impact this has on the way i access databases within my own applications. My goal is to allow people to use this pattern to reduce the code required to perform the common database tasks while reducing the coupling to the actual underlying database/ERM framework and making the flow of data throughout applications more seamless and hence more elegant.
I would also like to outline a few places this method falls down and what the pitfalls are around these specific circumstances.
To use the StaticVoid Repository pattern several things need to be set up.
Set up the kernel bindings
Kernel bindings tell the dependency injection framework how which concrete implementation to provide to classes when they request them.
Below is an example of the config required to setup Ninject
Note that we are binding generic implementations of IRepository<> and IRepositoryDataSource<> to concrete implementations provided by the library.
Using the repository
Repositories exist against a single entity type within your system. This means that you would consume a repository of a specific type.
Below is an MVC example of consuming a repository of geeks:
Note that the underlying data technology and type of repository are irrelevant to the controller accessing the repository.
Unit testing with repositories.
Because the individual technology and data source behind the repository is not implied in the usage of the repository it is really easy to test only the components which are important to the usage.
Below is an example of a unit test of a method which uses a repository:
Note the InMemoryRepositoryDataSource which is used in this example has some differences to the actual EF4.1 data source. One important difference is that when objects are added to an EF data source the foreign keys are populated in both directions whereas with the in memory repository they are only populated in the direction to which you are adding objects.
An example solution is avaliable here which shows the above examples in a running site.
I hope this post is helpful.