首页 > 解决方案 > 即时更改 appsettings.json 并将其输入 DI

问题描述

我正在为我的项目编写集成测试,我有以下场景。我有一个基类,所有测试类都从该基类继承。我的基类的构造函数如下所示:

public KrampHubServiceIntegrationTestBase()
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
            .Build();

        _apiSettings = config.GetSection("ApiSettings").Get<ApiSettings>();

        var builder = new WebHostBuilder()
            .UseStartup<Startup>()
            .UseConfiguration(config);

        var server = new TestServer(builder);
        _client = server.CreateClient();
    }

现在,当它调用.UseStartup()我想是它说进入我的另一个项目(Startup 是我正在测试的项目的一部分)并使用该 Startup(它注入不同的接口和实现的地方也有我的 appsettings.json 的值)。我需要做的是在启动开始工作之前修改 appsettings.json,即ApiSettings会话。我怎样才能做到这一点?提前致谢!

标签: c#asp.net-coremodel-view-controllerdependency-injectionappsettings

解决方案


推荐阅读