


.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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Microsoft's Windows 11 2022 Update (22H2) enables CoreIsolation's memory integrity protection by default. However, if you are running an older version of the operating system, such as Windows 11 2022 Update (22H1), you will need to turn this feature on manually. Turn on CoreIsolation's Memory Integrity feature in Windows 11 For users who don't know about Core Isolation, it's a security process designed to protect basic core activities on Windows from malicious programs by isolating them in memory. This process, combined with the memory integrity feature, ensures

Core has two meanings in computers: 1. The core, also known as the core, is the most important component of the CPU. All calculations, accepting storage commands, and processing data of the CPU are performed by the core; 2. Core, core is Intel's processor Name, Core is the processor brand launched by Intel after the Pentium processor. It has currently released twelfth generation Core processors.

Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure
![How to Fix Processor Thermal Trip Error in Windows 11/10 [Fix]](https://img.php.cn/upload/article/000/000/164/168169038621890.png?x-oss-process=image/resize,m_fill,h_207,w_330)
Most of the devices, such as laptops and desktops, have been heavily used by young gamers and coders for a long time. The system sometimes hangs due to application overload. This forces users to shut down their systems. This mainly happens to players who install and play heavy games. When the system tries to boot after force shutdown, it throws an error on a black screen as shown below: Below are the warnings detected during this boot. These can be viewed in the settings on the event log page. Warning: Processor thermal trip. Press any key to continue. ..These types of warning messages are always thrown when the processor temperature of a desktop or laptop exceeds its threshold temperature. Listed below are the reasons why this happens on Windows systems. Many heavy applications are in

If you are a .NET developer, you must be aware of the importance of optimizing functionality and performance in delivering high-quality software. By making expert use of the provided resources and reducing website load times, you not only create a pleasant experience for your users but also reduce infrastructure costs.

With the launch of .NETCore, .NET developers have a new opportunity to easily write and run .NET applications on multiple operating systems. This article will delve into how to use .NETCore to achieve cross-platform application development, and share best practice experience on operating systems such as Windows, Linux, and macOS. 1. Prepare the development environment. To start cross-platform application development, you first need to prepare the development environment for each target platform. Windows On Windows, you can install .NETCoreSDK through Visual Studio. After installation is complete, you can create and run .NETCore projects through Visual Studio. Li

In terms of high-concurrency request processing, .NETASP.NETCoreWebAPI performs better than JavaSpringMVC. The reasons include: AOT early compilation, which reduces startup time; more refined memory management, where developers are responsible for allocating and releasing object memory.
