Reputation: 95
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
{
}
Upvotes: 2
Views: 5778
Reputation: 17024
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()
{
}
Upvotes: 7
Reputation: 152626
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>
.
Upvotes: 1