Implement Simple Injector with generic repository

淺唱寂寞╮ 提交于 2019-12-13 07:45:42

问题


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>>();
container.Verify();

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?


回答1:


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);


来源:https://stackoverflow.com/questions/40847409/implement-simple-injector-with-generic-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!