I'm trying to generalize some code so that it can be used between projects, but I'm having some trouble generating instances from templated classes.
public class GenericRepository<TEntity, TContext> : IGenericRepository<TEntity>, IDisposable
where TEntity : class
where TContext : DbContext, new ()
{
protected TContext Context;
public GenericRepository()
{
Context = new TContext();
}
public virtual TEntity Create()
{
return Context.Set<TEntity>().Create();
}
// etc.
}
public interface IPlan
{
int PlanId { get; set; }
string Name { get; set; }
DateTime Modified { get; set; }
DateTime Created { get; set; }
event PropertyChangedEventHandler PropertyChanged;
}
public partial class Session : DataErrorInfo, INotifyPropertyChanged, IPlan
{
// Stuff to implement IPlan
}
IPlan and Generic repository are in the common code base, and Session is project-specific. So I want to be able to do something like this:
// These both work correctly
SimpleIoc.Default.Register<IPlan, Session>();
SimpleIoc.Default.Register<IGenericRepository<Session>, GenericRepository<Session, EMTVSEntities>>();
// Tried this one ...
SimpleIoc.Default.Register<IGenericRepository<IPlan>, GenericRepository<Session, EMTVSEntities>>();
Ultimately what I want is to be able to call this last one and get the context like this ...
var ctx = ServiceLocator.Current.GetInstance<IGenericRepository<IPlan>>();
But I get the following message: Unable to cast object of type 'GenericRepository2[Session,EMTVSEntities]' to type 'IGenericRepository
1[IPlan]'.
I understand it can't match the two types to do a case, but is there a way to get a specific instance from one identified by an interface using the templated type GenericRepository?