无法在控制台应用程序 .NET Core 中使用 IOptions

Cannot use IOptions in console app .NET Core

我有一个控制台应用程序,我正在其中构建配置

IConfiguration config = new ConfigurationBuilder()
   .AddJsonFile("appsettings.json", true, true)
   .Build();

var services = new ServiceCollection();
services.AddOptions();
services.Configure<ResourceConfiguration>(config.GetSection("ResourceConfiguration"));

这行不通

  Error CS1503: Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<ResourceConfiguration>' (29, 55)

我在使用中有以下内容(以及我自己的命名空间)

使用Microsoft.Extensions.Configuration; 使用 Microsoft.Extensions.DependencyInjection; 使用系统; 使用 System.IO;

IConfiguration config = new ConfigurationBuilder()
   .AddJsonFile("appsettings.json", true, true)
   .Build();

Returns IConfigurationRoot 可能是哪个问题?

我做错了什么?

这是 .NET Core 3.1

保罗

您可能缺少包裹 Microsoft.Extensions.Options.ConfigurationExtensions

我已经使用 .NET 6 创建了一个控制台应用程序来帮助您。

检查下面的代码,让我们知道它是否有效。 =)

AppSettings.json

{
    "SETUP_OPTIONS": 
    {
        "MyProperty": 100,
        "MyProperty2": "Success!"
    }
}

需要使用

using Microsoft.Extensions.Options;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

设置选项class

public class SetupOptions
{
    public const string ConfigKey = "SETUP_OPTIONS";

    public int MyProperty { get; set; }
    public string MyProperty2 { get; set; }
}

Program.cs

static async Task Main(string[] args)
{
    IConfiguration configuration = new ConfigurationBuilder()
        .SetBasePath(currentDirectory)
        .AddJsonFile("appsettings.json", optional: false)
        .Build();

    var serviceCollection = new ServiceCollection();
    ConfigureServices(serviceCollection, configuration);

    var serviceProvider = serviceCollection.BuildServiceProvider();

    await serviceProvider.GetService<MyAppClass>().RunAsync(args);
}

private static void ConfigureServices(ServiceCollection serviceCollection, IConfiguration configuration)
{
    // AppSettings IOptions configuration
    serviceCollection.AddOptions<SetupOptions>().Bind(configuration.GetSection(SetupOptions.ConfigKey));

    serviceCollection.AddTransient<MyAppClass>();
}

MyAppClass.cs

public class MyAppClass
{
    private readonly SetupOptions _setupOptions;

    // Inject IOptions in your constructor
    public MyAppClass(IOptions<SetupOptions> setupOptions)
    {
        _setupOptions = setupOptions?.Value;
    }

    public async Task RunAsync(string[] args)
    {
        // Use your Setup Options value loaded from appsettings file.
        var myPropertyValue = _setupOptions.MyProperty;
    }
}