Genericizing the repository
This repository is great, but do we really want to repeat this logic and all these tests for every single data model that we need to be retrieved from some data source? The answer is no; if you find yourself doing the same thing over and over as a developer, you are doing something wrong.
So, how can we protect ourselves from that drudgery?
One way is to use generics. Let's refactor the SpeakerRepository
to use generics, this will also involve refactoring many of the tests to make them apply to the GenericRepository
instead of the concrete SpeakerRepository
.
Step one – abstract interface
In the IRepository
, everywhere we use Speaker
we need to replace it with C# generics:
public interface IRepository<T> { T Create(T item); T Get(int id); IQueryable<T> GetAll(); T Update(T item); void Delete(T item); }
This change will cause a break in the SpeakerRepository
that we need to fix. Right now, we are chasing the compiler and leaning on it to tell us...