.NET 实现将配置节点映射为自定义实体

本篇内容将演示如何在.Net(Net6及以上版本都支持)中实现将配置节点信息映射到对应实体。

创建配置节点

打开配置文件 appsettings.json,添加Redis配置信息。

{
  "RedisConfig": {
    "Server": "127.0.0.1",
    "Port": "6379",
    "DbId": 4,
    "UserName": "",
    "Password": "123456"
  }
}

创建配置文件实体类

public class OptionsSetting
{
    public RedisConfig RedisConfig { get; set; }
}

/// <summary>
/// Redis连接配置
/// </summary>
public class RedisConfig
{
    /// <summary>
    /// 服务端IP
    /// </summary>
    public string Server { get; set; }

    /// <summary>
    /// 端口
    /// </summary>
    public string Port { get; set; }

    /// <summary>
    /// Db编号
    /// </summary>
    public int DbId { get; set; }

    /// <summary>
    /// 用户名
    /// </summary>
    public string UserName { get; set; }

    /// <summary>
    /// 密码
    /// </summary>
    public string Password { get; set; }
}

方式一:依赖注入

  1. 绑定对象到Model
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<OptionsSetting>(builder.Configuration);
  1. 依赖注入
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
  private OptionsSetting OptionsSetting { get; set; }
  public HomeController(IOptions<OptionsSetting> options)
  {
      OptionsSetting = options.Value;
  }

  [HttpGet]
  public IActionResult Get()
  {
     RedisConfig redisConfig = OptionsSetting.RedisConfig;
     return OK();
  }
}

此时redisConfig就可以读取到配置文件节点数据。

方式二:静态类全局访问

  1. 创建InternalApp类文件

注意:如果文件是放在公共层,非Web层,可以安装Microsoft.AspNetCore.Authentication.JwtBearer包

 public static class InternalApp
 {
    /// <summary>
    /// 应用服务
    /// </summary>
    public static IServiceProvider ServiceProvider;
     
    public static void ConfigureApplication(this IHost app)
    {
        ServiceProvider = app.Services;
    }
 }
  1. 创建App类文件
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

public static class App
 {
     /// <summary>
     /// 全局配置文件
     /// </summary>
     public static OptionsSetting OptionsSetting => CatchOrDefault(() => ServiceProvider?.GetService<IOptions<OptionsSetting>>()?.Value);

     /// <summary>
     /// 服务提供器
     /// </summary>
     public static IServiceProvider ServiceProvider => InternalApp.ServiceProvider;


     /// <summary>
     /// 处理获取对象异常问题
     /// </summary>
     /// <typeparam name="T">类型</typeparam>
     /// <param name="action">获取对象委托</param>
     /// <param name="defaultValue">默认值</param>
     /// <returns>T</returns>
     private static T CatchOrDefault<T>(Func<T> action, T defaultValue = null) where T : class
     {
         try
         {
             return action();
         }
         catch
         {
             return defaultValue ?? null;
         }
     }
 }
  1. 绑定对象到Model、调用InternalApp类文件里的ConfigureApplication方法
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<OptionsSetting>(builder.Configuration);

var app = builder.Build();
app.ConfigureApplication();
  1. 直接使用
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
  [HttpGet]
  public IActionResult Get()
  {
     RedisConfig redisConfig = App.OptionsSetting.RedisConfig;
     return OK();
  }
}

此时redisConfig就可以读取到配置文件节点数据。

注意事项

以上两种方式如果是通过 VS 运行或者 dotnet run 命令运行,则默认读取的是 appsettings.Development.json 文件配置,如果该文件没有配置节点,则读取的是 appsettings.json 配置。如果想要强制读appsettings.json文件,则需要在绑定对象到Model前加上以下这段代码。

builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
posted @ 2025-07-20 12:35  相遇就是有缘  阅读(24)  评论(0)    收藏  举报