I have this GenericRepository class that I intend to use as a base-class for my other repositories. I build my generic methods like this…
public class GenericRepository
{
public void Insert<TEntity>(TEntity entity) where TEntity : class
{
var collection = GetCollection<TEntity>();
collection.Save<TEntity>(entity);
}
}
Now, my question…
Is it possible to inherit the GenericRepository in a way such that you do not have to explicitly include the generic type when calling each method? E.g. if I had a UserRepository : GenericRepository, I would be able to write:
var repo = new UserRepository();
repo.Insert(user);
// Instead of
repo.Insert<User>(user);
You don’t need to do anything. This just works, if
useris indeed of typeUser, because the compiler will infer the type.But you really should change your class hierarchy to this, i.e. use the generic parameter to the class level:
Background:
When you extend your repository, you will see, why:
This code would be possible, but wouldn’t make any sense, because each repository instance should only be responsible for one type: