DotNetCore跨平台~在appsettings.json里自定义配置项

来源:互联网 发布:adidas旗舰店淘宝真假 编辑:程序博客网 时间:2024/06/10 06:31

回到目录

DotNetCore里一切都是依赖注入的,对于appsettings这个可扩展的配置对象也不例外,它位于项目根目录,一般在startup里去注册它,在类中通过构造方法注入来获取当前的对象,以便去使用它,当然我们也可以自己去构建和使用它,下面我就来总结一下。

传统方法,startup注入,构造方法使用

1 注意配置类

   public class RedisConfiguration    {        #region 属性成员        /// <summary>        /// 文件上传路径        /// </summary>        public string Host { get; set; }        /// <summary>        /// 允许上传的文件格式        /// </summary>        public string Password { get; set; }        /// <summary>        /// 图片上传最大值KB        /// </summary>        public int IsProxy { get; set; }        #endregion    }

2 在appsettings里添加它的内容

{  "Logging": {    "IncludeScopes": false,    "Debug": {      "LogLevel": {        "Default": "Warning"      }    },    "Console": {      "LogLevel": {        "Default": "Warning"      }    }  },  "RedisConfiguration": {    "Host": "localhost:6379",    "Password": "bobo123#",    "IsProxy": "0"  }}

3 在控制器里使用它,当然你可以在基类中定义它的使用方式,但注入的入口还是在构造方法上

  public class ApiControllerBase : Controller    {        private readonly IOptions<RedisConfiguration> AppConfiguration;        public ApiControllerBase(IOptions<RedisConfiguration> appConfiguration)        {            AppConfiguration = appConfiguration;        }   }

这时,你的AppConfiguration在被加载后,就有值了,是在程序运行时被注入进来的!

属性中注入并且使用

appsetting的内容不变,只是在属性中去封装了配置注入与获取的过程,注意,为了考虑性能,你可以把它的建立和获取做成单例,这点我就不设计了!

       public RedisConfiguration AppConfigurations        {            get            {                var config = new ConfigurationBuilder()                             .AddInMemoryCollection()                             .SetBasePath(Directory.GetCurrentDirectory())                             .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)                             .Build();                var sp = new ServiceCollection().AddOptions().Configure<RedisConfiguration>(                         config.GetSection("RedisConfiguration")).BuildServiceProvider();                var _appConfiguration = sp.GetService<IOptions<RedisConfiguration>>();                return _appConfiguration.Value;            }        }

 在控制器上,可以直接使用它了,我这个属性是做在所有控制器的父类上的。

        [HttpGet]        public IEnumerable<string> Get()        {            return new string[] {                AppConfigurations.Host,                AppConfigurations.Password,                AppConfigurations.IsProxy.ToString()            };        }

感谢各位的阅读!

对于.net core的研究我们还在继续,希望core2.0,standard2.0不会让我们失望!

听说它已经实现了.net frameworks 4.6.1所有的功能!

回到目录

阅读全文
0 0
原创粉丝点击