日常生活的交流与学习

首页 新随笔 联系 管理

注册配置实例

Registers a configuration instance which TOptions will bind against.

AppSettings.cs

public class AppSettings
{
    public const string Key = nameof(AppSettings);
    public string ConnectionString { get; set; }
    public int Port { get; set; }
}

Program.cs

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);

使用方式1

// 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
AppSettings appSettings = builder.Configuration.GetSection(AppSettings.Key).Get<AppSettings>()!;
Console.WriteLine(appSettings.Port);
Console.WriteLine(appSettings.ConnectionString);

WeatherForecastController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace AspDemo.Server.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing",
            "Bracing",
            "Chilly",
            "Cool",
            "Mild",
            "Warm",
            "Balmy",
            "Hot",
            "Sweltering",
            "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly AppSettings _appSettings;


        //                                                                           👇👇👇👇👇👇👇👇👇👇👇👇👇
        public WeatherForecastController(ILogger<WeatherForecastController> logger , IOptions<AppSettings> appSettings)
        {
            _logger = logger;
            // 👇👇👇👇👇👇👇👇👇👇👇👇
            _appSettings = appSettings.Value;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {


            // 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
            System.Console.WriteLine(_appSettings.ConnectionString);
            System.Console.WriteLine(_appSettings.Port);

            return Enumerable
                .Range(1, 5)
                .Select(index => new WeatherForecast
                {
                    Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                    TemperatureC = Random.Shared.Next(-20, 55),
                    Summary = Summaries[Random.Shared.Next(Summaries.Length)]
                })
                .ToArray();
        }
    }
}
posted on 2024-09-06 08:00  lazycookie  阅读(4)  评论(0编辑  收藏  举报