Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

configuration - Actually read AppSettings in ConfigureServices phase in ASP.NET Core

I need to setup a few dependencies (services) in the ConfigureServices method in an ASP.NET Core 1.0 web application.

The issue is that based on the new JSON configuration I need to setup a service or another.

I can't seem to actually read the settings in the ConfigureServices phase of the app lifetime:

public void ConfigureServices(IServiceCollection services)
{
    var section = Configuration.GetSection("MySettings"); // this does not actually hold the settings
    services.Configure<MySettingsClass>(section); // this is a setup instruction, I can't actually get a MySettingsClass instance with the settings
    // ...
    // set up services
    services.AddSingleton(typeof(ISomething), typeof(ConcreteSomething));
}

I would need to actually read that section and decide what to register for ISomething (maybe a different type than ConcreteSomething).

question from:https://stackoverflow.com/questions/40470556/actually-read-appsettings-in-configureservices-phase-in-asp-net-core

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That is the way you can get the typed settings from appSettings.json right in ConfigureServices method:

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

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<MySettings>(Configuration.GetSection(nameof(MySettings)));
        services.AddSingleton(Configuration);

        // ...

        var settings = Configuration.GetSection(nameof(MySettings)).Get<MySettings>();
        int maxNumberOfSomething = settings.MaxNumberOfSomething;

        // ...
    }

    // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...