更新时间:2022-03-17 23:15:36
您可以将IConfigurationRoot注入到可以在测试项目中使用本地配置文件的位置.您将丢失默认的特定于环境的配置替代,这是新项目模板中的默认替代,但是我个人无论如何都不会将其用于配置管理(建议使用非承诺的appsetting.local.json,这对于开发人员而言是唯一的)并连接到CI服务器.
You could just inject the IConfigurationRoot where you could just use a local config file in the test project. You'd lose the default environment-specific config overrides that are the default in the new project template, but I personally don't use those for configuration management anyway (preferring non-committed appsetting.local.json instead which can be unique to developers and to the CI server).
var configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true)
.AddInMemoryCollection(new Dictionary<string, string>
{
{"myConfig:setting1", "value1"},
{"myConfig:setting2", "value2"}
})
.Build();
var server = new TestServer(new WebHostBuilder()
.UseUrls("http://localhost:5001")
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.ConfigureServices(services => services.AddSingleton(configuration)));
对于启动:
public class Startup
{
public Startup(IConfigurationRoot configuration)
{
this.Configuration = configuration;
}
...
}
修改:
尽管这确实可行,但似乎也无法在运行时识别配置文件更改,从而中断了IOptionsSnapshot
配置注入.我将离开这个答案,但也将继续挖掘更好的方法,而无需注入自定义服务来仅支持测试/夹具特定的配置替代.
While this does work, it also seems to break IOptionsSnapshot
configuration injections from recognizing config file changes at run-time. I'm going to leave this answer, but will also keep digging for better way without injecting a custom service just to support test/fixture-specific config overrides.