在 Asp.Net Core 的 AddTransient 方法中使用泛型

Use generics in AddTransient method in Asp.Net Core

使用 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>)'

我错过了什么?

为了constrain一个类型参数是一个引用类型使用class类型约束。 EG

where T1 : class, IDbContext

但是为什么要将 DbContext 添加为 Transient 而不是 Scoped?