• [转].NET Core配置文件加载与DI注入配置数据


    本文转自:http://www.cnblogs.com/skig/p/6079187.html

    .NET Core配置文件

    在以前.NET中配置文件都是以App.config / Web.config等XML格式的配置文件,而.NET Core中建议使用以JSON为格式的配置文件,因为使用起来更加方面灵活,而且可以使用.NET Core中的DI注入配置数据。

    使用:

    复制代码
    1             var config = new ConfigurationBuilder()
    2                 .AddInMemoryCollection()    //将配置文件的数据加载到内存中
    3                 .SetBasePath(Directory.GetCurrentDirectory())   //指定配置文件所在的目录
    4                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)  //指定加载的配置文件
    5                 .Build();    //编译成对象  
    6             Console.WriteLine(config["test"]);  //获取配置中的数据
    7             config["test"] = "test test";   //修改配置对象的数据,配置对象的数据是可以被修改的
    8             Console.WriteLine(config["test11"]);    //获取配置文件中不存在数据也是不会报错的
    9             Console.WriteLine(config["theKey:nextKey"]);    //获取:theKey -> nextKey 的值
    复制代码

    配置文件appsettings.json文件内容:

    1 {
    2   "test": "testVal",
    3   "theKey": {
    4     "nextKey": "keyVal"
    5   }
    6 }

     注意:

    ConfigurationBuilder需要添加包:"Microsoft.Extensions.Configuration"

    AddJsonFile需要添加包:"Microsoft.Extensions.Configuration.Json"

    与DI配合使用

    复制代码
     1             var sp = new ServiceCollection()
     2                 .AddOptions()   //注入IOptions<T>,这样就可以在DI容器中获取IOptions<T>了
     3                 .Configure<TestCls>(config.GetSection("TestCls"))   //注入配置数据
     4                 //也可以对注入的配置数据进行修改
     5                 .Configure<TestCls>(t =>
     6                 {
     7                     t.Name = "Jame"; //修改Name的值
     8                 })
     9                 .BuildServiceProvider();    //编译
    10 
    11             var test = sp.GetService<IOptions<TestCls>>();    //获取注入的配置数据对象
    12             Console.WriteLine(JsonConvert.SerializeObject(test.Value));    //{"Name":"Jame","Age":123}
    13 
    14             //下面的代码中检验Configure注入的配置数据对象是单例模式的(.NET Core中DI容器的三种生命周期:Singleton(单例), Scoped(作用域), Transient(瞬态))
    15             var test1 = sp.GetService<IOptions<TestCls>>();
    16             Console.WriteLine(test == test1);   //true
    17             //创建一个新的作用域获取配置数据对象
    18             var test2 = sp.GetService<IServiceScopeFactory>().CreateScope().ServiceProvider.GetService<IOptions<TestCls>>();
    19             Console.WriteLine(test == test2);   //true
    复制代码

     配置测试类:

    1         public class TestCls
    2         {
    3             public string Name { get; set; }
    4             public int Age { get; set; }
    5         }

    appsettings.json中的内容:

    1 {
    2   "TestCls": {
    3     "Name": "Tom",
    4     "Age": 123
    5   }
    6 }

    注意:

    ServiceCollection需要添加包: "Microsoft.Extensions.DependencyInjection"

    AddOptions需要添加包: "Microsoft.Extensions.Options.ConfigurationExtensions"

    ASP.NET Core中使用

    Startup.cs -> Startup构造方法中进行初始化配置文件:

    1             var builder = new ConfigurationBuilder()
    2                 .AddInMemoryCollection()
    3                 .SetBasePath(env.ContentRootPath)
    4                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    5                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
    6             Configuration = builder.Build();

    Startup.cs -> ConfigureServices方法中进行注入配置数据:

    1             services.AddOptions()        //注入IOptions<T>
    2                 .Configure<TestCls>(Configuration.GetSection(nameof(TestCls)))
    3                 .Configure<TestCls>(test =>
    4                 {
    5                     test.Name = "Jame"; //修改Name的值
    6                 });

    配置文件中的配置数据:

    复制代码
     1 {
     2   "Logging": {
     3     "IncludeScopes": false,
     4     "LogLevel": {
     5       "Default": "Debug",
     6       "System": "Information",
     7       "Microsoft": "Information"
     8     }
     9   },
    10   "TestCls": {
    11     "Name": "Tom",
    12     "Age": 123
    13   }
    14 }
    复制代码

    注入到控制器中:

    复制代码
     1     [Route("api/[controller]")]
     2     public class ValuesController : Controller
     3     {
     4         IOptions<TestCls> _test;
     5         public ValuesController(IOptions<TestCls> test)
     6         {
     7             _test = test;
     8         }
     9         [HttpGet]
    10         public string Gets()
    11         {
    12             return JsonConvert.SerializeObject(_test.Value);
    13         }
    复制代码

    访问:/api/values

    显示:{"Name":"Jame","Age":123}

    作者:skig
    欢迎转载,但请注明出处。如果大家有任何疑问,可以给我留言,我会及时回复。
  • 相关阅读:
    我所理解的三次握手
    网络舆情——初步了解
    【转载】位运算的密码
    【转载】基础排序算法简介
    【原创】关于hashcode和equals的不同实现对HashMap和HashSet集合类的影响的探究
    【原创】Java移位运算
    【原创】MapReduce计数器
    【原创】Hadoop机架感知对性能调优的理解
    【原创】一个复制本地文件到Hadoop文件系统的实例
    【转载】JAVA IO 流的总结
  • 原文地址:https://www.cnblogs.com/freeliver54/p/6265579.html
Copyright © 2020-2023  润新知