我如何使用带有 Ninject 的泛型将接口绑定到 class?

How do I bind interface to class using generics with Ninject?

我创建了一个通用接口和一个通用存储库。我正在尝试将这些泛型与我现有的架构一起使用,以改进和简化我的依赖注入实现。

绑定在没有泛型实现的情况下工作。 我似乎找不到哪里出错了。

下面是我如何尝试使用 Ninject 实现这些泛型。

我收到的错误是:

///Error message: Unable to cast object of type 'DataRepository' to type 'IDataRepository'.

这是通用的 repo 和接口

//generic interface
     public interface IGenericRepository<T> where T : class
    {
        IQueryable<T> GetAll();
        IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
        void Add(T entity);
        void Delete(T entity);
        void Edit(T entity);
        void Save();
    }


//generic repo
    public abstract class GenericRepository<T> : IGenericRepository<T> where T : class 
    {  
          ////removed the implementation to shorten post...

我在这里创建了使用泛型的 repo 和接口

//repo
    public class DataRepository : GenericRepository<IDataRepository>
    {
        public IQueryable<MainSearchResult> SearchMain(){ //.... stuff here}
    }

    //interface
    public interface IDataRepository : IGenericRepository<MainSearchResult>
    {
        IQueryable<MainSearchResult> SearchMain(){ //.... stuff here}
    }

在../App_Start 下的静态class NinjectWebCommon 中,我在RegisterServices(IKernel kernel) 方法中绑定了classes。 我已经尝试了几种绑定方式,但我仍然收到 "Unable to cast object type..." 错误。

    private static void RegisterServices(IKernel kernel)
            {
                // current failed attempts
kernel.Bind(typeof(IGenericRepository<>)).To(typeof(GenericRepository<>));
                kernel.Bind(typeof(IDataRepository)).To(typeof(DataRepository));

                // failed attempts
                //kernel.Bind<IDataRepository>().To<GenericRepository<DataRepository>>();
                //kernel.Bind<IDataRepository>().To<GenericRepository<DataRepository>>();
            } 

有没有人看到我做错了什么会导致这个问题?

问题是 DataRepository 没有继承自 IDataRepository

像这样应该没问题:

public class DataRepository : GenericRepository<MainSearchResult>, IDataRepository
{
    ...