当前位置: 首页 > 工具软件 > AgileConfig > 使用案例 >

.NET 开源配置组件 AgileConfig 初体验

文鸣
2023-12-01

在客户端程序使用
这里使用了asp net core web项目示例,首先需要安装客户端组件,执行一下命令或者通过Nuget安装。

Install-Package AgileConfig.Client
然后修改appsetting.json 文件

{
“AgileConfig”: {
“appId”: “LogService”,
“secret”: “123456”,
“nodes”: “http://localhost:5000,http://localhost:5001”//多个节点使用逗号分隔
}
}
然后修改 Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
var configClient = new ConfigClient();
config.AddAgileConfig(configClient);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
});
准备工作完成,接下来就要开始使用了,我们在配置项页面上面添加配置,然后选中点击上线。

然后可以在代码中使用注入的 IConfiguration 获取配置即可

[Route("[controller]/[action]")]
public class HomeController : ControllerBase
{
private readonly IConfiguration _config;

    public HomeController(IConfiguration config)
    {
        _config = config; 
    }

    [HttpGet]
    public IActionResult Index()
    {
        var value = _config["AgileKey"];

        return Ok(new { value });
    }

然后启动程序,就可以尽情使用 AgileConfig 了,在页面上修改配置的话,我们的客户端配置也是实时修改的。

在配置页面上的配置都是字符串键值对的,那对于Json字符串应该怎么处理呢, 我们可以使用 Tuhu.Extensions.Configuration.ValueBinder.Json 扩展,通过Nuget安装即可,然后修改Startup.cs 文件

public void ConfigureServices(IServiceCollection services)
{
services.ConfigureJsonValue("", Configuration.GetSection(“LogOptions”));
}
LogOptions:

public class LogOptions : IOptions
{
public string Level { get; set; }

    public int Count { get; set; }

    public LogOptions Value => this;

}
这样我们就可以在代码中,使用注入的 IOptions 来获取读取配置。
USB Microphone https://www.soft-voice.com/
Wooden Speakers https://www.zeshuiplatform.com/
亚马逊测评 www.yisuping.cn
深圳网站建设www.sz886.com

 类似资料: