Используйте дженерики в методе AddTransient в Asp. Net Core - PullRequest
0 голосов
/ 17 апреля 2020

Использование Asp. Net Ядро У меня есть следующее:

services.AddTransient<Context>(x => new Context("my connection", new ContextMapper()));

Я хотел бы использовать метод расширения и дженерики, поэтому я создал:

public static void AddContext<T1, T2>(this IServiceCollection services, String connectionString) 
    where T1 : IDbContext 
    where T2 : DbContextMapper {

  T2 contextMapper = (T2)Activator.CreateInstance(typeof(T2));

  T1 context = (T1)Activator.CreateInstance(typeof(T1), new Object[] { connectionString, contextMapper });

  services.AddTransient<T1>(x => context);

}

Но Я получаю сообщение об ошибке:

The type 'T1' must be a reference type in order to use it as parameter 'TService' in the generic type or method 'ServiceCollectionServiceExtensions.AddTransient<TService>(IServiceCollection, Func<IServiceProvider, TService>)'

Что мне не хватает?

1 Ответ

1 голос
/ 17 апреля 2020

К ограничение параметр типа, который будет ссылочным типом, использует ограничение типа class. EG

where T1 : class, IDbContext

Но почему вы добавляете DbContext как Transient вместо Scoped?

...