Reputation: 744
I first made a new repository interface for each of my entities e.g. IClientRepository. I then made a class for each entity e.g. SqlClientRepository. I did this for a lot of my entities and then realized that they all had the same methods: Add, Update, Delete, GetAll.
So I realized that I should probably just make the one interface instead of making a separate one for each.
The problem is that now my dependency injection won't work since I can only map the interface to one repository:
Bind<IClientRepository>().To<SqlClientsRepository>().WithConstructorArgument("connectionString", WebConfigurationManager.ConnectionStrings["MyDb"].ConnectionString);
The only work-around I can see is to combine all of the repositories or go back to my first attempt. Using the first attempt would also allow me to change the return types for certain entities e.g. IClientRepository.Add() could return the new client's id, and some other entities might not need that.
Appreciate any thoughts.
Upvotes: 0
Views: 205
Reputation: 3854
one solution is to make the Interface generic. this way, it's general enough, while still being flexible.
Upvotes: 0
Reputation: 4736
It's hard to say for sure without knowing what you are trying to accomplish. In my latest project, there is one repository per class, IRepository<T>
. That might get you out of your IoC binding trouble.
Upvotes: 0
Reputation: 15196
You could have your ClientRepository implement both your BaseRepository and a specific IClientRepository. That way your Base can have the usual Add/Remove etc and your IClientRepository could have specialized methods (or be empty in some cases probably). Your IoC could resolve using your IClientRepository.
This is how i do it:
public class CustomerRepository : BaseRepository<Customer>, ICustomerRepository {...}
and
unityContainer.RegisterType<ICustomerRepository, CustomerRepository>();
Good luck :)
Upvotes: 2
Reputation: 88355
A common approach for repositories is to create a base interface like "IRepository" with the common CRUD methods or methods that all repos can use. Then for each specific repository create a new interface that derives from the base interface but includes the domain-specific methods for that repo. The same thing can be done for a base Repository implementation and the more specific implementation classes. This way you have a common place for common functionality, but you still have specific interfaces for each concrete domain-specific repository implementation.
Upvotes: 0