.NET Core 通过注入的方式获取 appsettings.json 中的信息

配置文件是开发过程中必不可少的元素,今天讲到的就是如何优雅的获取配置文件信息,下面是实践步骤:

1.在 appsettings.json 中找个地方写入配置文件信息

"TestConfigration": {
    "Item1": "1",
    "Item2": "2"
}

2.新建对应类,用于存储配置信息

public class TestConfigration
{
    public string Item1 { get; set; }
    public string Item2 { get; set; }
}

3.在 Startup 类中注册 TestConfigration 类

services.ConfigureOption(_appConfiguration.GetSection("TestConfigration"), () => new TestConfigration());

4.在需要的类中注入 IOptions<TestConfigration> _testConfigration 类,这样配置文件中的信息就会被加载,效果如下:

发布了87 篇原创文章 · 获赞 69 · 访问量 60万+

猜你喜欢

转载自blog.csdn.net/S2T11Enterprise/article/details/96288588