FYI Repository Pattern C#

kudchikarsk

New member
Joined
May 17, 2020
Messages
1
Programming Experience
3-5
What Is Repository Pattern C#?
A Repository in C# mediates between the domain and data mapping layers (like Entity Framework). It allows you to pull a record or number of records out of datasets, and then have those records to work on acting like an in-memory domain object collection, and you can also update or delete records within those data set, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes.
Repository pattern C# is a way to implement data access by encapsulating the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer.
Repository pattern C# also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.
Repository pattern C# is mostly used where we need to modify the data before passing to the next stage.
here’s an awesome graph that illustrates the idea:
No alt text provided for this image


Why Repository Pattern C#?
  • Increase testability: Repository systems are good for testing. One reason is that you can use Dependency Injection. Basically, you create an interface for your repository, and you reference the interface for it when you are making the object. Then you can later make a fake object (using moq for instance) which implements that interface. Using something like StructureMap you can then bind the proper type to that interface. Boom you’ve just taken a dependence out of the equation and replaced it with something testable.
  • Easily swapped out with various data stores without changing the API: For example, in one instance, you may need to retrieve data from the database, in other cases you may need to retrieve something from a third-party API, or perhaps there’s some other place from which you need to retrieve data. Regardless, the idea behind the repository pattern is that whatever sits behind it doesn’t matter so long as the API it provides works for the layer of the application calling into it.
For more information on how to create a repository using EF read my blog post Repository Pattern C#.
 
I tend to fall into the group of people who consider the Repository pattern to be anti-pattern, but mostly because most people implement it wrong.

This is a good read though before you decide where you stand on the Repository pattern:
 
Back
Top Bottom