【问题标题】:How do I bind interface to class using generics with Ninject?如何使用带有 Ninject 的泛型将接口绑定到类?
【发布时间】:2016-05-02 19:26:55
【问题描述】:

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

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

以下是我尝试使用 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 和接口

//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 下的静态类 NinjectWebCommon 中,我在 RegisterServices(IKernel kernel) 方法中绑定类。 我尝试了多种绑定方式,但仍收到“无法转换对象类型...”错误。

    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?好像没有
  • 你想要的可能是class DataRepository : GenericRepository&lt;MainSearchResult&gt;, IDataRepository
  • 这是正确的。您应该将其作为答案提交
  • 防止具有额外功能的特定存储库实现,例如自定义查询。这样做违反了 SOLID 原则,并导致维护噩梦。这些问题和正确的解决方案在here 进行了描述。

标签: c# asp.net generics dependency-injection ninject


【解决方案1】:

问题是DataRepository 不是从IDataRepository 继承的。

这样的应该没问题:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多