SimpleIOC и дженерики

Я пытаюсь обобщить некоторый код, чтобы его можно было использовать между проектами, но у меня возникли некоторые проблемы при создании экземпляров из шаблонных классов.

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 и Generic репозиторий находятся в общей базе кода, а Session зависит от проекта. Поэтому я хочу иметь возможность сделать что-то вроде этого:

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

В конечном счете, я хочу, чтобы я мог назвать этот последний и получить такой контекст...

var ctx = ServiceLocator.Current.GetInstance<IGenericRepository<IPlan>>();

Но я получаю следующее сообщение: Невозможно привести объект типа 'GenericRepository2[Session,EMTVSEntities]' to type 'IGenericRepository1 [IPlan]".

Я понимаю, что это не может совпасть с двумя типами, чтобы сделать случай, но есть ли способ получить конкретный экземпляр от идентификатора, идентифицированного интерфейсом, используя шаблонный тип GenericRepository?

0 ответов

Другие вопросы по тегам