Asp.net Core与类库读取配置文件信息的方法

2019-05-25 10:04:41丽君

所以自己动手写了一个工具类

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using System;

namespace Common
{
 public class ConfigurationHelper
 {
  public IConfiguration config { get; set; }
  public ConfigurationHelper()
  {
   IHostingEnvironment env = MyServiceProvider.ServiceProvider.GetRequiredService<IHostingEnvironment>();
   config = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    .AddEnvironmentVariables()
    .Build();
  }
  public T GetAppSettings<T>(string key) where T : class, new()
  {
   var appconfig = new ServiceCollection()
    .AddOptions()
    .Configure<T>(config.GetSection(key))
    .BuildServiceProvider()
    .GetService<IOptions<T>>()
    .Value;
   return appconfig;
  }
 }
 //我比较喜欢单独放这个类,但是这样放更明显
 public class MyServiceProvider
 {
  public static IServiceProvider ServiceProvider { get; set; }
 }
}

使用这个类的话需要在StartUp的Configure中添加

 MyServiceProvider.ServiceProvider = app.ApplicationServices;

然后就可以在任何地方使用此类读取配置文件信息了,而且由于ConfigurationHelper初始化时已经默认加载环境变量,所以同时具备多环境功能。

 string path = new ConfigurationHelper().config["RedisPath"];
   SettingPath pathss = new ConfigurationHelper().GetAppSettings<SettingPath>("SettingPath");

参考

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/environments?view=aspnetcore-2.1 https://www.jb51.net/article/125674.htm

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。