Внедрить DbContext в хранилище на основе типа generi c с помощью Simple Injector - PullRequest
1 голос
/ 16 марта 2020

Предположим, у меня есть следующий обобщенный c класс:

public class Repository<T> : IRepository<T> where T : class
{
    private DbContext Context { get; set; }

    public Repository(DbContext context)
    {
        Context = context;
    }
}

И я регистрирую два различных dbcontext, как показано ниже, используя SimpleInjector:

container.Register<ContextA>(
    ()=> new ContextA(SqlServerDbContextOptionsExtensions.UseSqlServer(
        new DbContextOptionsBuilder(), sqlConnection).Options));

container.Register<ContextB>(
    () => new ContextB(SqlServerDbContextOptionsExtensions.UseSqlServer(
        new DbContextOptionsBuilder(), sqlConnection).Options));

И затем у меня есть следующее регистрация для dbContext:

container.RegisterConditional(
    typeof(DbContext),
    typeof(ContextA),
    c=> c.Consumer.ImplementationType.GenericTypeArguments
        .Any(r => r.Namespace == "NameSpace.ContextA"));

container.RegisterConditional(
    typeof(DbContext),
    typeof(ContextB),
    c => c.Consumer.ImplementationType.GenericTypeArguments
        .Any(r => r.Namespace == "NameSpace.ContextB"));

Когда коды достигают container.RegisterConditional , он выдает ошибку и жалуется на наличие ContextA, имеющего два конструктора.

Учитывая, что я уже ввел ContextA и ContextB, каков наилучший способ ввести соответствующее DbContext для Repository на основе его значения аргумента generi c?

Обновление

Я хочу ввести DbContext в Repository<T>, основываясь на типе, переданном для инициализации Repository<T>.

Так Я мог бы иметь:

IRepository<Entity1> ...

Какой Entity1 может быть в NameSpace.ContextA .

1 Ответ

1 голос
/ 16 марта 2020

Вам необходимо использовать перегрузку RegisterConditional, которая принимает Registration. Таким образом, вы можете заключить лямбда-выражение в Registration следующим образом:

var contextARegistration =
    Lifestyle.Scoped.CreateRegistration(
        () => new ContextA(
            SqlServerDbContextOptionsExtensions.UseSqlServer(
                new DbContextOptionsBuilder(), sqlConnection).Options),
        container);

container.RegisterConditional(
    typeof(DbContext),
    contextARegistration,
    c => c.Consumer.ImplementationType.GenericTypeArguments
             .Any(r => r.Namespace == "NameSpace.ContextA"));

var contextBRegistration =
    Lifestyle.Scoped.CreateRegistration(
        () => new ContextB(
            SqlServerDbContextOptionsExtensions.UseSqlServer(
                new DbContextOptionsBuilder(), sqlConnection).Options),
        container);

container.RegisterConditional(
    typeof(DbContext),
    contextBRegistration,
    c => c.Consumer.ImplementationType.GenericTypeArguments
             .Any(r => r.Namespace == "NameSpace.ContextB"));

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...