如何在泛型方法中使用 IOptions<T> 作为泛型参数

Jen*_*nni 2 c# asp.net-core

我正在尝试创建一个用作IOptions<T>参数的通用方法,但代码似乎无效。

Visual Studio 显示以下消息:

TConfig 必须是具有非无参数构造函数的非抽象类型,才能将其用作泛型类型或方法中的参数“TOption”'IOptions<TOptions>'

任何有关如何解决此问题的建议将不胜感激。谢谢!!

public static IServiceCollection AddConfigurations<TConfig>(
    this IServiceCollection services, IConfiguration configuration, 
    IOptions<TConfig> options) 
    where TConfig : class
{
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*rdt 7

问题是,它IOptions有以下限制:

where TOptions : class, new()
Run Code Online (Sandbox Code Playgroud)

所以你new()也需要这个约束( ):

public static IServiceCollection AddConfigurations<TConfig>(
    this IServiceCollection services, IConfiguration configuration, 
    IOptions<TConfig> options) 
    where TConfig : class, new()
{
}
Run Code Online (Sandbox Code Playgroud)