search
HomeBackend DevelopmentC#.Net Tutorial.NET Core configuration file loading and DI injection of configuration data

.NET Core configuration file

In the past, configuration files in .NET were all in XML format such as App.config/Web.config. However, in .NET Core, it is recommended to use configuration files in JSON format because it is easier to use It is more flexible and can use DI in .NET Core to inject configuration data.

Use:

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

Configuration file appsettings.json file content:

{
  "test": "testVal",
  "theKey": {
    "nextKey": "keyVal"
  }
}

Note:

ConfigurationBuilder needs to add the package: "Microsoft.Extensions.Configuration"

AddJsonFile needs to add the package: "Microsoft.Extensions.Configuration.Json"

Use with DI

var sp = new ServiceCollection()
                .AddOptions()   //注入IOptions<T>,这样就可以在DI容器中获取IOptions<T>了
                .Configure<TestCls>(config.GetSection("TestCls"))   //注入配置数据
                //也可以对注入的配置数据进行修改
                .Configure<TestCls>(t =>
                {
                    t.Name = "Jame"; //修改Name的值
                })
                .BuildServiceProvider();    //编译

            var test = sp.GetService<IOptions<TestCls>>();    //获取注入的配置数据对象
            Console.WriteLine(JsonConvert.SerializeObject(test.Value));    //{"Name":"Jame","Age":123}

            //下面的代码中检验Configure注入的配置数据对象是单例模式的(.NET Core中DI容器的三种生命周期:Singleton(单例), Scoped(作用域), Transient(瞬态))
            var test1 = sp.GetService<IOptions<TestCls>>();
            Console.WriteLine(test == test1);   //true
            //创建一个新的作用域获取配置数据对象
            var test2 = sp.GetService<IServiceScopeFactory>().CreateScope().ServiceProvider.GetService<IOptions<TestCls>>();
            Console.WriteLine(test == test2);   //true

Configuration test class:

         public class TestCls
         {
             public string Name { get; set; }
             public int Age { get; set; }
         }

Contents in appsettings.json:

{
  "TestCls": {
    "Name": "Tom",
    "Age": 123
  }
}

Note:

ServiceCollection needs to add the package: "Microsoft.Extensions.DependencyInjection"

AddOptions needs to add the package : "Microsoft.Extensions.Options.ConfigurationExtensions"

ASP.NET Core is used in

Startup.cs -> Initialization configuration file in the Startup construction method:

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

Startup.cs -> ConfigureServices method Inject configuration data:

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

Configuration data in the configuration file:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "TestCls": {
    "Name": "Tom",
    "Age": 123
  }
}

Inject into the controller:

[Route("api/[controller]")]
    public class ValuesController : Controller
    {
        IOptions<TestCls> _test;
        public ValuesController(IOptions<TestCls> test)
        {
            _test = test;
        }
        [HttpGet]
        public string Gets()
        {
            return JsonConvert.SerializeObject(_test.Value);
        }

Access: /api/values

Display: {"Name":"Jame","Age":123 }

【Related recommendations】

1. Graphic verification code for .Net Core

2. .NET Core CLI tool documentation dotnet-publish

3. Detailed introduction to ZKEACMS for .Net Core

4. Share the example code of using forms verification in .net MVC

5. How to make http request under .net core?

6. An example tutorial of running ZKEACMS on CentOS

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools