Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using generic interface in the repository pattern

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.

like image 696
Unknown Avatar asked Apr 12 '26 01:04

Unknown


1 Answers

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
    }
}
like image 156
John Allers Avatar answered Apr 13 '26 15:04

John Allers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!