docker-compose 在我的 C# 测试中找不到我的环境变量

Doj*_*owl 4 c# xunit docker docker-compose asp.net-core

我有一个简单的 C# 应用程序,它使用 docker-compose 运行 API。

当使用 docker-compose 在我的本地机器上运行测试时,我收到一个连接字符串错误,因为 docker 没有找到我的环境变量。

我的测试使用 XUnit 运行,我使用 XUnit 依赖注入方法和启动文件,在这个文件中注入了连接字符串。

我不知道我缺少什么,很乐意获得帮助!

.env 文件:

ConnectionStrings__Default=MyDatabaseConnection
Run Code Online (Sandbox Code Playgroud)

在 yaml 文件中,这是与环境变量相关的代码。

env_file:
  - .env
environment:
  - ACCEPT_EULA=Y
  - ConnectionStrings__Default=${ConnectionStrings__Default}
Run Code Online (Sandbox Code Playgroud)

在测试启动类中

public void ConfigureServices(IServiceCollection services)
{
    Configuration = new ConfigurationBuilder().Build();
    services.AddDbContext<SqlDbContext>(
        options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
}
Run Code Online (Sandbox Code Playgroud)

Mis*_*sky 5

看起来您缺少应该调用的AddEnvironmentVariables方法,以便让配置了解.env文件及其环境变量。

public void ConfigureServices(IServiceCollection services)
{
    Configuration = new ConfigurationBuilder()
        .AddEnvironmentVariables()
        .Build();

    services.AddDbContext<SqlDbContext>(
        options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
}
Run Code Online (Sandbox Code Playgroud)

另外,我建议您移动要在构造函数中初始化的 Configuration 字段。