Dervis Findik Dervis Findik - 1 month ago 24
C# Question

Implement Simple Injector with generic repository

I have some problem to implement SimpleInjector with my generic Repository.

I have an interface

IRepository<T> where T : class
and an abstract class
abstract class Repository<C, T> : IRepository<T> where T : class where C : DbContext
which implements the interface. Finally I have my entity repositories which inherit the abstract class. Here's a concret example:

public interface IRepository<T> where T : class
IQueryable<T> GetAll();
IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
void Add(T entity);
void Remove(T entity);

public abstract class Repository<C, T> : IRepository<T>
where T : class where C : DbContext, new()
private C _context = new C();
public C Context
get { return _context; }
set { _context = value; }
public virtual IQueryable<T> GetAll()
IQueryable<T> query = _context.Set<T>();
return query;

public class PortalRepository : Repository<SequoiaEntities, Portal>

In my global.asax.cs file, under Application_Start() function, I added :

Container container = new Container();
container.Register<IRepository<Portal>, Repository<SequoiaEntities, Portal>>();

When I launch my project, Simple Injector tries to verify the container and I get an error :

Additional information: The given type
Repository<SequoiaEntities, Portal>
is not a concrete type. Please use one of the other overloads to register this type.

Is there a way to implement Simple Injector with generic class or I have to pass by specific class?


The Register<TService, TImpementation>() method allows you to specify a concrete type (TImplementation) that will be created by Simple Injector when the specified service (TService) is requested. The specified implementation Repository<SequoiaEntities, Portal> however is marked as abstract. This disallows Simple Injector from creating it; abstract classes can not be created. The CLR does not permit this.

You do have a concrete type PortalRepository however, and I believe it is your goal to return that type. Your configuration should therefore look as follows:

container.Register<IRepository<Portal>, PortalRepository>();

Alternatively, you can make use of Simple Injector's batch-registration facilities and register all your repositories in one call:

Assembly[] assemblies = new[] { typeof(PortalRepository).Assembly };

container.Register(typeof(IRepository<>), assemblies);