apolloconfig / apollo.net

Apollo .Net Client
Apache License 2.0
481 stars 167 forks source link

Apollo配置能否调整优先级低于本地文件appsettings.json配置和命令行 #210

Open zhaobotao opened 1 year ago

zhaobotao commented 1 year ago

项目接入Apollo后, 相同Key下Apollo的配置优先级最高,因为按照官方.net core配置的介绍,Apollo是最后加载的,所以优先级高。这样会导致本地appsettings.json和命令行的优先级会低于Apollo配置,对于开发本地调试或其他场景不太方便;虽然通过代码清除Provider:config.Sources.Clear(),然后再重新按照顺序加载;这样可以解决问题,但比较麻烦。不知道Apollo.Net能否支持指定Provider优先级,像Spring一样。

pengweiqhca commented 1 year ago

你可以在ConfigureHostConfiguration里添加Apollo,这样就比appsettings.json和命令行优先级低;或者builder.Sources.Insert(0)

zhaobotao commented 1 year ago

谢谢:)。 试了下ConfigureHostConfiguration好像不行,可能我弄错了? builder.Host.ConfigureHostConfiguration(builder => { builder.AddApollo(builder.Build().GetSection("apollo")); // 能用builder.Build().GetSection("apollo"),说明已经有appsetting.json的配置了,除非全部clear掉 });

另外使用builder.Sources.Insert(0),不知道怎么做?我要从现有的builder.Source获取到Apollo的Provider吗,然后移除掉重新Insert到0吗,如果这样也挺麻烦的。

pengweiqhca commented 1 year ago

默认apollo需要的配置会配置在appsettings.json里,如果是这样,AddApollo()你最好使用一个带IApolloOptions参数的重载

zhaobotao commented 1 year ago

试过了,不行;在刚进入这个方法之前,其他的Provider已经加载进去了。 builder.Host.ConfigureHostConfiguration(builder => { builder.AddApollo("SampleApp","http://apollo.inner.dev.xxxx.com:8080") .AddNamespace("application.json"); });

pengweiqhca commented 1 year ago

没关系啊,appsettings.json是在ConfigureAppConfiguration中添加的

zhaobotao commented 1 year ago

试过了,不可以,在进入ConfigureHostConfiguration之前appsettings.json等provider已经存在了。见图: apollogit 我新开了全新的项目也是这样。环境是.net 6

zhaobotao commented 1 year ago

刚试了下,按照您说的办法.net 3.1的写法可以,但是按照.net 6不行。看了下源码,应该是var builder = WebApplication.CreateBuilder(args)默认给创建好了,在ConfigureHostConfiguration之前。官方.net 6也有解释: apollogit2 所以现在如果想做到降低apollo配置的优先级低于本地文件和命令行,可能还是我之前的想法,罗列builder.Sources,按照希望的重新排序,不知道还有其他更好的办法吗。

czd890 commented 1 year ago

我也碰到类似的情况, 需要手动调整顺序, 研究了一番找不到很好的方式. 然后就有了这个issue #203 Net6+ 调整IList的顺序之后Apollo的热更新不工作了

如果本地调试要覆盖一些参数, 建议在launchSettings.json里面通过环境变量注入. 或者来一个appsettings.local.json 文件作为优先级最后的source. 然后这个文件排除源代码控制.