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

标签 c# asp.net-core

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

Visual Studio 显示以下消息:

TConfig must be a non-abstract type with a non-parameterless constructor in order to use it as a parameter 'TOption' in the generic type or method 'IOptions<TOptions>'

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

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

最佳答案

问题是,IOptions具有以下约束:

where TOptions : class, new()

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

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

关于c# - 如何在泛型方法中使用 IOptions<T> 作为泛型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56677936/

相关文章:

c# - 如何在运行时获取构建配置?

c# - 有效关闭 WCF 4 channel 的正确方法

asp.net-web-api - ASP.net Core RC2 Web API POST - 何时使用 Create、CreatedAtAction 与 CreatedAtRoute?

c# - 使用两个应用程序时的 Azure AD 身份验证重定向循环(cookie 错误)

c# - 服务器端 SignalR 连接在长时间正常运行后失败

c# - 如何在 Entity Framework Core 中执行 SQL 查询而不修改上下文类

c# - 为什么 EF Core 一对多关系集合返回 null?

c# - 将没有 LinqExpression 的自定义助手转换为使用 LinqExpression 的自定义助手

c# - 使用 OpenXML 将图像插入 DocX 并设置大小

c# - 当注册名称不唯一时,有什么方法可以从 ROT 获取对象?