2016-05-02 46 views
1

我创建了一个通用接口和一个通用的回购。我试图利用这些泛型与我现有的体系结构来改进和简化我的依赖注入实现。如何使用泛型与Ninject绑定接口类?

绑定在没有泛型实现的情况下工作。 我似乎无法找到我要出错的地方。

下面是我如何试图与Ninject实现这些泛型。我接收

有错误是:

///错误消息: 无法转换类型的对象 'DataRepository' 为类型 'IDataRepository'。

这里是通用回购和接口

//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 
    public class DataRepository : GenericRepository<IDataRepository> 
    { 
     public IQueryable<MainSearchResult> SearchMain(){ //.... stuff here} 
    } 

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

在静态类NinjectWebCommon ../App_Start下我绑定了RegisterServices(IKernel内核)方法中的类。 我试过几种绑定方式,但我仍然收到“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>>(); 
      } 

有谁看到任何我做错了会导致这个问题?

+0

是否'DataRepository'从'IDataRepository'继承?看起来它不是 – MaKCbIMKo

+2

可能你想要的是'class DataRepository:GenericRepository ,IDataRepository' –

+0

这是正确的。你应该提交它作为答案 – ironman

回答

2

问题是DataRepository不是从IDataRepository继承。

像这样的东西应该是罚款:

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