How to use IOptions<T> as a generic parameter in a generic method

Viewed 5011

I am trying to create a generic method that use IOptions<T> as parameter but the code seems to be invalid.

Visual studio displays the following message:

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>'

Any suggestion on how to fix this would be appreciated. Thanks!!

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

The problem is, that IOptions has the following contraint:

where TOptions : class, new()

So you need this constraint (new()) too:

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

Look at the constraints on T in the definition of IOptions<T>. The constraints on AddConfigurations<TConfig> need to have at least those restrictions on TConfig since it uses IOptions<TConfig>.

Related