Creating a Generic, Reusable Repository in OrmLite
I like to use OrmLite for my MS SQL repositories because it's Type safe and easy to write repository methods.
Recently, I needed to create two basic repository methods for a new model. I had a pretty standard, basic requirement, and it wouldn't have been difficult to spin up a new repository, inject it into the
Container and move on with my day.
I felt, though, that this was a mistake. I was repeating myself over and over again with my repositories, and it felt wrong.
So how could I DRY this up? We'll get into that, but first, let's take a look at what I normally do when I create a new repo.
The Tried and True Approach:
The repository would have looked something like this.
And Dependency Injection would have looked like this:
And then to use
ThingRepository, you simply inject it into whatever class you need it.
Again, all of this would be fine, and I could rinse and repeat this pattern all day long.
But who wants to keep stacking up repository after repository when the methods are basically all the same.
The New and Shiny Approach:
I figured out that most of my repositories had the same methods being recreated over and over again.
So let's do it again, right? No more repeating the same pattern! Onward and updward!
Repository Take 2:
We need to create an Open Generic class, which the above class accomplishes.
We can now register the new repository in
Startup.cs like so:
The only way to register the open generic repository and implementation is to use
Let's go back and update
Having done this, we now have the following methods available to us:
You could inject multiple
IRepository<TModel> implementations into the same class.
There's no need to create class after class with the exact same methods.
If there was a need for more methods, they could be added to
IRepository, or you could create a
ThingRepository and extend
Repository<Thing> like so:
You now have a flexible, extensible generic repository that can take care of basic CRUD operations and allows for extension over time when it's necessary.