码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET Core 配置文件(无处不在的依赖注入)

时间:2017-08-16 13:17:44      阅读:625      评论:0      收藏:0      [点我收藏+]

标签:key   pass   .json   配置文件   ati   roo   view   sof   .net   

前烟:

  .NET Core 中取消了以往的 XML 节点配置文件,改用了 *.json 格式。

  在 Startup.cs 文件中,构造方法 build appsetting.json 文件,

  本文主要对解析配置文件的官方工具类做总结;

 

一、appsettings.json 文件

  在新建的 Core Web 项目中,默认会有一个全局的配置变量:IConfigurationRoot 

  提供了索引器、GetSection 方法;

{
  "Host": "http://localhost:5966/",
  "Title": "Hello World",
  "SiteKeywords": "asp.net, c#, asp.net core, asp.net entityframework core",
  "Description": "DotNetClub: asp.net core",
  "ConnectionString": "Data Source=localhost;Initial Catalog=dbName;User Id=userName;Password=pwd;",

  "Redis": {
    "EndPoints": [ "localhost", "6379" ],
    "Password": "",
    "Db": ""
  },

  "Site": {
    "Host": "http://localhost:5966",
    "Title": "Hello World",
    "Description": "DotNetClub: asp.net core",
    "AllowRegister": true,
    "VerifyRegisterUser": false,
    "AdminUserList": []
  },

  "CookieName": "DotNetClub.User",

  "Categories": [
    {
      "Key": "share",
      "Name": "分享"
    },
    {
      "Key": "ask",
      "Name": "问答"
    },
    {
      "Key": "job",
      "Name": "招聘"
    }
  ]
}

  获取根节点数据:

  Configuration["ConnectionString"]

  Configuration["Title"]

  获取节点数据:

  services.Configure<RedisOptions>(Configuration.GetSection("Redis").Bind)

 

  重点记录的是这个 Microsoft.Extensions.Options.ConfigurationExtensions 提供的 IOptions

  Configure 方法可以将 appsettings.json 中的配置绑定某一个实体对象上。如:

技术分享
    public class RedisOptions
    {
        /// <summary>
        /// Redis end points, such as "{host or ip}:{port}"
        /// </summary>
        public string[] EndPoints { get; set; }

        /// <summary>
        /// Redis password
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// Default redis database
        /// </summary>
        public int Db { get; set; }
    }
View Code

  完成这样的一个过程就是 Configure 类实现了一个依赖注入;

 

ASP.NET Core 配置文件(无处不在的依赖注入)

标签:key   pass   .json   配置文件   ati   roo   view   sof   .net   

原文地址:http://www.cnblogs.com/loongsoft/p/7372724.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!