配置文件如何注册引用
注册配置文件的形式
注册方式
// 第一种注册方式:注册配置文件
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
AppSettings appSettings = builder.Configuration.GetSection(AppSettings.Key).Get<AppSettings>()!;
Console.WriteLine(appSettings.Port);
Console.WriteLine(appSettings.ConnectionString);
使用方式
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace AspDemo.Server.Controllers;
[ApiController]
[Route("[controller]")]
public class AppSettingTwoController : ControllerBase
{
// 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
private readonly AppSettings _appSettings;
// 👇👇👇👇👇👇👇👇👇👇👇
public AppSettingTwoController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}
[HttpGet]
public IActionResult Get()
{
System.Console.WriteLine(_appSettings.ConnectionString);
System.Console.WriteLine(_appSettings.Port);
return Ok(_appSettings);
}
}
将配置文件注册成单例模式
注册方式
// 第二种注册方式:将配置文件注册成单例模式
builder.Services.AddSingleton(s => s.GetRequiredService<IOptions<AppSettings>>().Value);
使用方式
using Microsoft.AspNetCore.Mvc;
namespace AspDemo.Server.Controllers;
[ApiController]
[Route("[controller]")]
public class AppSettingController : ControllerBase
{
// 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
private readonly AppSettings _appSettings;
// 👇👇👇👇👇👇👇👇👇
public AppSettingController(AppSettings appSettings)
{
// 👇👇👇👇👇👇👇👇👇
_appSettings = appSettings;
}
[HttpGet]
public IActionResult Get()
{
System.Console.WriteLine(_appSettings.ConnectionString);
System.Console.WriteLine(_appSettings.Port);
return Ok(_appSettings);
}
}