Ninject MVC 中的通用存储库

Ninject Generic Repository in MVC

我有一个通用存储库界面,如您所见:

  public interface IEntityRepository<T> where T : class
{

    IQueryable<T> GetAll();
    IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
    bool Add(T entity);
    bool Delete(T entity);
    bool Edit(T entity);

}

它的小鬼

 public abstract class Repository<C, T> :
       IEntityRepository<T> where T : class where C : WelfateContext, new()
    {

        private C _entities = new C();
        public C Context
        {

            get { return _entities; }
            set { _entities = value; }
        }

        public virtual IQueryable<T> GetAll()
        {

            IQueryable<T> query = _entities.Set<T>();
            return query;
        }

        public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {

            IQueryable<T> query = _entities.Set<T>().Where(predicate);
            return query;
        }

        public virtual bool Add(T entity)
        {
            _entities.Set<T>().Add(entity);
            _entities.SaveChanges();
            return true;
        }

        public virtual bool Delete(T entity)
        {
            _entities.Set<T>().Remove(entity);
            _entities.SaveChanges();
            return true;
        }

        public virtual bool Edit(T entity)
        {
            _entities.Entry(entity).State = EntityState.Modified;
            _entities.SaveChanges();
            return true;
        }

    }

如您所见,我在我的控制器中使用了它:

private IEntityRepository<Employee> employeeService;

    public EmployeeController(IEntityRepository<Employee> _employeeService)
    {

        _employeeService = employeeService;
    }

我收到这个错误:

Error activating IEntityRepository{Employee} using binding from IEntityRepository{Employee} to Repository{WelfateContext, Employee}
No constructor was available to create an instance of the implementation type.

Activation path:
 2) Injection of dependency IEntityRepository{Employee} into parameter _employeeService of constructor of type EmployeeController
 1) Request for EmployeeController

Suggestions:
 1) Ensure that the implementation type has a public constructor.
 2) If you have implemented the Singleton pattern, use a binding with InSingletonScope() instead.

这是我的 ninject 绑定

 private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<WelfateContext>().To<WelfateContext>().InRequestScope();
            kernel.Bind<IEntityRepository<Employee>>().To<Repository<WelfateContext, Employee>>();
            kernel.Bind<IEmployeeService>().To<EmployeeService>().InRequestScope();
            kernel.Bind<IEmployeeDomainService>().To<EmployeeDomainService>().InRequestScope();

        }

将构造函数添加到存储库

   private readonly C _entities;
   public Repository(C context)
   {
     _entities = context;
   }

那么你不需要这个代码

 public C Context
        {

            get { return _entities; }
            set { _entities = value; }
        }