.net Core Console App stark typisierte Konfiguration

Sep 17 2020

Es gibt eine Antwort Stackoverflow hier wie auf einer .net Kernkonsolenanwendung stark typisierte - Konfiguration erstellen , aber meine Frage ist , wie geben Sie diese stark typisierte Konfiguration auf andere Dienstleistungen;

etwas wie das

static void Main(string[] args)
{
    //...
    .AddSingleton<IMyService, MyService>()
}

public class MyService
{
    private readonly IConfiguration _configuration;
    public MyService (IConfiguration configuration)
    {
        _configuration = configuration;
    }
}

Antworten

AthanasiosKataras Sep 16 2020 at 23:07

Hier ist ein Beispiel aus der MS-Dokumentation https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1#accessing-options-during-startup

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddOptions<MyConfigOptions>()
            .Bind(Configuration.GetSection(MyConfigOptions.MyConfig))
            .ValidateDataAnnotations();

        services.AddControllersWithViews();
    }

Und Konsument:

public HomeController(IOptions<MyConfigOptions> config,
                          ILogger<HomeController> logger)