0

Scenario:

public interface IEntity {
    int Id {get; set;};
}

public interface IRepository<T> where T: class, IEntity {
    //repo crud stuffs here
}

public class RepositoryBase<T> : IRepository<T> where T : class, IEntity {
    //general EF crud implementation
}

public class MyEntity : IEntity {
    //implementation and other properties
}

public interface IMyEntityRepository : IRepository<MyEntity> {
    //any extending stuff here
}

public class MyEntityRepository : RepositoryBase<MyEntity>, IMyEntityRepository {
    //implementation here
}

public interface IBusinessLogic<T> where T : class, IEntity {
}

public class BusinessLogicBase<T> : IBusinessLogic<T> where T : class, IEntity {
    private readonly IRepository<T> _baseRepo;
    private readonly IList<IRepository<IEntity> _repositories;

    public BusinessLogicBase(IRepository<T> baseRepo, params IRepository<IEntity>[] repositories) {
        _baseRepo = baseRepo;
        _repositories = repositories;
    }

    //some standard business logic methods that resolve the repositories based on navigation property types and call

    private IRepository<U> ResolveRepository<U>() where U: class, IEntity {
        IRepository<U> found = null;
        foreach (IRepository<IEntity> repository in _repositories) {
            if (repository.IsFor(typeof(U))) {
                found = repository as IRepository<U>;
                break;
            }
        }
        return found;
    }
}

public interface IMyEntityBL : IBusinessLogic<MyEntity> {
    //extended stuff here
}

public class SomeOtherEntity : IEntity {
}

public interface ISomeOtherEntityRepository : IRepository<SomeOtherEntity> {
}

public interface SomeOtherEntityRepository : RepositoryBase<SomeOtherEntity>, ISomeOtherEntityRepository {
}

public class MyEntityBL : BusinessLogicBase<MyEntity>, IMyEntityBL {
    public MyEntityBL(IRepository<MyEntity> baseRepo, ISomeOtherEntityRepository someOtherEntityRepo) : base(baseRepo, someOtherEntityRepo) {
        //ERROR IS HERE WHEN TRYING TO PASS ISomeOtherEntityRepository to base
    }
    //implementation etc here
}

Why can I not pass ISomeOtherEntityRepository to base? I get the "is not assignable parameter type" error. It implements IRepository and SomeOtherEntity is an IEntity so I don't see why what I'm attempting is invalid. Can someone please advise?

weagle08
  • 1,763
  • 1
  • 18
  • 27
  • Why are all the `class` and `interface` keywords missing? Always copy/paste working code. – H H Jul 02 '17 at 16:59

1 Answers1

2
public interface IRepository<out T> 
   where T : class, IEntity

See this answer for a lengthy explanation about co- and contra-variance.

H H
  • 263,252
  • 30
  • 330
  • 514