. NET 4.X in advance with. NET Core configuration mode and hot reload configuration

Source: Internet
Author: User

1. Preface

In the current era of promoting microservices and serverless, traditional. Net application configuration patterns often rely on an XML file called Web. config, which is disconnected from the age of extensibility and readability. Of course, I will not encourage you to move all applications to. NET core at once, and this article will maximize the benefits without introducing the. NET core development model.

Before we get started, let's start by talking about the advantages and minimal dependencies of the. Net Core configuration mode.

Benefits of 1.1. Net Core Configuration mode
    • supports multiple formats , such as Json, INI, YAML, system environment variables, etc.
    • No longer dependent on Web. config, multiple configuration formats can be used simultaneously
    • Support Hot Reload configuration , modify configuration can not restart the application
1.2 Minimum dependencies
nuget install  Microsoft.Extensions.Configurationnuget install Microsoft.Extensions.Configuration.Bindernuget install Castle.Windsor (其他 IOC 框架均可)

If you are installing the latest package, you may encounter an issue where the Microsoft.Extensions.Configuration series Nuget packages cannot be installed, depending on the. NET version of the current app, please refer to installing the corresponding version (. NET 4.5 is not currently supported The following applications).

Because I prefer a highly readable Json file, I also install Microsoft.Extensions.Configuration.Json the Nuget package.

2. Sample Tutorials

This article implements the configuration mode of. Net Core and the hot reload configuration on the basis of ABP 2.1.3 , and a more detailed procedure can refer to my commit history on Github.

2.1 Load Configuration

The core of the. NET Core configuration mode is an interface object named Iconfigurationroot, which requires the creation of an instance of Iconfigurationroot after loading various configuration formats in the application portal, in a traditional. NET Web application Global.asax.cs Value.

// ConfigurationExtenion.AppConfiguration 为一个静态的 IConfigurationRoot 实例。 ConfigurationExtenion.AppConfiguration = new ConfigurationBuilder()                .AddJsonFile("appsetting.json", optional: false, reloadOnChange: true)                .AddJsonFile("appsetting01.json", optional: true, reloadOnChange: false)                .Build();

To explain briefly, we need (in the root directory) a JSON file named "Appsetting.json", which is also overloaded when modified ConfigurationExtenion.AppConfiguration . The opposite "Appsetting01.json" is allowed to not exist, even if it exists, and is not overloaded when modified.

2.2 Read Configuration node

After loading the configuration, we need to read the configuration, in which IConfigurationRoot all the configured information is present in a node, we can get the corresponding type object according to the node name.

        /// <summary>        /// 获取节点配置        /// </summary>        /// <typeparam name="TService"></typeparam>        /// <param name="config"></param>        /// <param name="sectionName"></param>        /// <returns></returns>        internal static TService GetSectionObject<TService>(IConfigurationRoot config, String sectionName)        {            var section = config.GetSection(sectionName);            if (section == null)            {                throw new ArgumentException($" {sectionName} 未绑定,无法获取到配置节点信息!");            }            return section.Get<TService>();        }

Let's say we have one of these "Appsetting.json" files:

{    "RedisConfiguration": {      "InstanceDbId": 14,      "InstanceRedisConnectionString": "127.0.0.1"    },    "MongoDbConfiguration": {      "ConnectionString": "mongodb://127.0.0.1:27017/?connectTimeoutMS=300000",      "DatatabaseName": "local"    }  }

If we want to get the MongoDbConfiguration ConnectionString value below, then we can get this:

var connectionString= GetSectionObject<String>(ConfigurationExtenion.AppConfiguration,"MongoDbConfiguration:ConnectionString");
2.3 Design Configuration Classes

In traditional. Net applications, we tend to use a static variable to store configuration information. In the case of IOC, a better approach is to design a class to hold the configuration, such as the JSON file above, we can design the following two classes (the selective paste Json in Visual Studio automatically generates objects):

    public class RedisConfiguration    {        public int InstanceDbId { get; set; }        public string InstanceRedisConnectionString { get; set; }    }    public class MongodbConfiguration    {        public string ConnectionString { get; set; }        public string DatatabaseName { get; set; }    }
2.4 Registering the configuration

In order to implement the hot reload configuration instead of a constant value, we need to obtain the configuration class in the IOC using the factory method. You can do this in Windsor:

        /// <summary>        /// 注册方法        /// </summary>        /// <typeparam name="TService"></typeparam>        /// <param name="ioc"></param>        /// <param name="factoryMethod"></param>        private static void Register<TService>(IIocManager ioc,                                     Func<TService> factoryMethod) where TService : class        {            ioc.IocContainer                .Register(                    Component.For<TService>()                        .UsingFactoryMethod(factoryMethod)                        .LifestyleTransient() //这里的生命周期是瞬时的,单例不可以吗?                );        }

Combined with the previous get Configuration node, we can combine two static methods to create a new static method that is more convenient for us to use.

        /// <summary>        /// 注册配置        /// </summary>        /// <typeparam name="TService"></typeparam>        /// <param name="ioc"></param>        /// <param name="config"></param>        /// <param name="sectionName"></param>        internal static void InitConfigService<TService>(IIocManager ioc, IConfigurationRoot config, String sectionName) where TService : class        {            Register(ioc, () =>            {                var service = GetSectionObject<TService>(config, sectionName);                return service;            });        }

For the first two configuration classes, we can inject this:

   ConfigurationExtenion.InitConfigService<RedisConfiguration>(IocManager,ConfigurationExtenion.AppConfiguration, "RedisConfiguration");   ConfigurationExtenion.InitConfigService<MongodbConfiguration>(IocManager, ConfigurationExtenion.AppConfiguration, "MongoDbConfiguration");
2.5 Getting the configuration

I'm here to add a controller method gets the RedisConfiguration object, which uses property injection to get the specified configuration class and returns to the page.

       public String GetRedisConfig()        {            var redisConfig = IocManager.Instance.Resolve<RedisConfiguration>();            return redisConfig.ToJsonString();        }

You can see that the page shows the structure of a Json file with one model:

2.6 Hot Reload Configuration

Unlike. NET Core, just slightly modifying the next Json file in a. NET 4.X Web app will cause the entire app to restart (modifying the Web. config also restarts), so I renamed "Appsetting.json" to "appsetting." Conf ", modify some values at run time, and re-access the controller, you can see that the corresponding value has changed.

Be aware of IIS security configuration, Json or INI may be able to get directly through HTTP!

3. Conclusion

By simply using the. NET core configuration mode, we can feel the power of it, and if you know more about. NET core, and how you feel the contrast between the two, you can compare it to an article I wrote earlier. For hot-reload configurations, more in. NET core is to make use of ioptionssnapshot, and in order to introduce the features of. NET core as little as possible, here simply uses the IOC's features. Of course, defining a global static instance without using any IOC (if you're afraid to introduce an IOC) IConfigurationRoot is also a compromise scenario.

. NET 4.X in advance with. NET Core configuration mode and hot reload configuration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.