实际在ASP.NET Core的ConfigureServices阶段读取AppSettings

编程入门 行业动态 更新时间:2024-10-25 00:31:51
本文介绍了实际在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).

推荐答案

这是从appSettings.json方法中直接从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

本文发布于:2023-11-02 15:02:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552711.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:阶段   NET   ASP   Core   AppSettings

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!