2
votes

I created a generic Interface and a generic repo. I'm trying to utilize these generics with my existing architecture to improve and simplify my dependency injection implementation.

The binding works without the generics implementation. I can't seem to find where I'm going wrong.

Below is how I'm trying to implement these generics with Ninject.

There error that I receive is:

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

Here is the generic repo and interface

//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...

Here I've created repo and interface that uses the generics

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

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

In the static class NinjectWebCommon under ../App_Start I'm binding the classes in the RegisterServices(IKernel kernel) method. I've tried several ways of binding but I continue to receive the "Unable to cast object type..." error.

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

Does anyone see anything that I'm doing wrong that would cause this issue?

1
Does DataRepository inherit from IDataRepository? Looks like it doesn't - MaKCbIMKo
probably what you want is class DataRepository : GenericRepository<MainSearchResult>, IDataRepository - Arturo Menchaca
that is correct. you should submit it as the answer - haydnD
Prevent having specific repository implementations that extra functionality such as custom queries. Doing so is in violation with the SOLID principles and leads to a maintenance nightmare. These problems and the right solution are described here. - Steven

1 Answers

2
votes

The problem is that DataRepository is not inheriting from IDataRepository.

Something like this should be fine:

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