在 ASP.NET Core 中的 ConfigureServices 阶段实际读取 AppSettings [英] Actually read AppSettings in ConfigureServices phase in ASP.NET Core

查看:43
本文介绍了在 ASP.NET Core 中的 ConfigureServices 阶段实际读取 AppSettings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 ASP.NET Core 1.0 Web 应用程序的 ConfigureServices 方法中设置一些依赖项(服务).

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

问题是基于新的 JSON 配置,我需要设置服务或其他服务.

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

我似乎无法实际读取应用生命周期的 ConfigureServices 阶段的设置:

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));
}

我需要实际阅读该部分并决定为 ISomething 注册什么(可能与 ConcreteSomething 的类型不同).

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

推荐答案

这就是您可以在 ConfigureServices 方法中从 appSettings.json 获取类型化设置的方式:

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;

        // ...
    }

    // ...
}

这篇关于在 ASP.NET Core 中的 ConfigureServices 阶段实际读取 AppSettings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆