首页 > 解决方案 > 使用泛型的构造函数中的参数创建类的实例

问题描述

使用 Asp.Net Core 3 有以下方法:

public static void AddLiteContext<TContext, TContextMapper>(this IServiceCollection services, String connection) 
  where TContext : ILiteContext 
  where TContextMapper : LiteContextMapper {

}

在此方法中,我需要以下内容:

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

但我需要基于泛型创建 Context 和 ContextMapper 的实例:

ILiteContext 
LiteContextMapper

请注意,类 Context 和类 ContextMapper 是这些泛型的实现:

public class Context : ILiteContext { }

public class ContextMapper : LiteContextMapper { }

我使用的方法如下:

services.AddLiteContext<Context, ContextMapper>(myConnection); 

我怎样才能做到这一点?

标签: c#asp.net-coreasp.net-core-3.0

解决方案


推荐阅读