I am currently developing an MVC 3 application with EF and the Repository pattern. I created a generic interface as follows:
interface IGenericRepository<T>
{
}
And an abstract class as follows:
abstract class GenericRepository<TContext ,T> : IGenericRepository<T>
where TContext : DbContext, new()
{
}
After that my repo inherits both of them like this:
interface ICardRepository : IGenericRepository<Card>
{
}
and
class CardRepository : GenericRepository<EfContext, Card>,
ICardRepository
{
}
With Unity I register the interface and the class like this:
container.RegisterType<ICardRepository, CardRepository>();
Now the question is: can I use IGenericRepository instead of ICardRepository?
Like this:
container.RegisterType<IGenericRepository<Card>, CardRepository>();
In theory I can, but as I still do not get how this pattern works I am not quite sure if I am not breaking or missing something.
One possible issue is now you will have to resolve IGenericRepository<Card>, instead of ICardRepository.
This will not work:
var cardRepository = container.Resolve<ICardRepository>();
Instead you will have to do this:
var cardRepository = container.Resolve<IGenericRepository<Card>>();
This also means that if you are doing something like constructor injection, you can't use:
public class SomethingDependentOnCardRepository
{
// The parameter type should be IGenericRepository<Card> instead,
// if you are using Unity to resolve this dependency.
public SomethingDependentOnCardRepository(ICardRepository cardRepository)
{
// code
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With