我有一个.NET Core WebApi项目.为了轻松阅读appsettings,我配置了要与DI一起注入的选项.这很好.但是,如果尝试使用通用类型参数调用Configure<>(),则会收到错误消息.
Argument 2: cannot convert from ‘Microsoft.Extensions.Configuration.IConfigurationSection’ to ‘System.Action’
除了Configure T(Action T configureconfigs)之外,该方法过载似乎不再可用.
为什么调用不适用于泛型类型参数?
启动文件
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
// services.AddMvc() etc...
services.AddOptions();
// Works fine
services.Configure<MyOption>(Configuration.GetSection(nameof(MyOption)));
}
private void AddOption<T>(IServiceCollection services)
{
// Wont work
services.Configure<T>(Configuration.GetSection(nameof(T)));
services.Configure<T>(Configuration.GetSection(""));
}
}
MyOption.cs
public class MyOption
{
public bool MyProp { get; set; }
}
appsettings.json
{
"MyOption": {
"MyProp": true
}
}
解决方法:
您需要像这样更改函数AddOption:
private void AddOption<T>(IServiceCollection services) where T : class
{
services.Configure<T>(Configuration.GetSection(typeof(T).Name));
}
您忘记了方法声明中的T:类
在您可以像下面那样使用此方法之后:
AddOption<MyOption>(services);