I have this method to get a generic repository out of a dictionary:
public readonly IDictionary<Type, IRepository> _repositories = new Dictionary<Type, IRepository>();
public IRepository GetRepository(Type type)
{
if (this._repositories.ContainsKey(type)) {
return this._repositories[type];
}
return null;
}
That works but I want it to work using generics so I tried:
public IRepository<T> GetRepository<T>() where T : class
{
var typeParameterType = typeof(T);
if (this._repositories.ContainsKey(typeParameterType)) {
return this._repositories[typeParameterType];
}
return null;
}
But I get an error like ‘Cannot implicitly convert type IRepository to IRepository<T>. An explicit conversion exists (are you missing a cast?)
Anybody know how to resolve this?
As the error suggests, you’ll need to either change
GetRepository‘s return type to the non-genericIRepository:Or, simply cast the return of
this._repositoriesto the generic typeIRepository<T>:Or possibly more appropriate: