.NET Aspire服务发现无法找到PostgreSQL服务器,求排查错误
使用.NET Aspire配置PostgreSQL和Web项目时,服务发现无法找到PostgreSQL服务器,抛出错误:
System.Net.Sockets.SocketException: 'No such host is known.'
AppHost配置代码:
var postgres = builder .AddPostgres("Postgres", port: 5432) .WithImageTag("latest") .WithContainerName("MyDatabase-PostgresDb-Aspire") .WithEnvironment("POSTGRES_USER", "postgres") .WithEnvironment("POSTGRES_PASSWORD", "postgrespassword") .WithEnvironment("POSTGRES_DB", "MyDatabase") .WithEnvironment("POSTGRES_HOST_AUTH_METHOD", "trust") .WithDataBindMount(source: "F:\\DockerVolumes\\Postgres\\Data", isReadOnly: false) .WithLifetime(ContainerLifetime.Persistent) .AddDatabase("MyDatabase"); var web = builder.AddProject<ArshidWeb>(nameof(ArshidWeb)) .WithExternalHttpEndpoints() .WithScalar().WithSwagger().WithOpenApi() .WaitFor(postgres) .WithReference(postgres);
连接字符串配置:
"ConnectionStrings": { "PostgresConnection":"Host=Postgres;Port=5432;Database=MyDatabase;Username=postgres;Password=postgrespassword;" }
注:使用docker-compose.yml和Dockerfile时该配置运行正常,但.NET Aspire环境下出错。
问题出在硬编码连接字符串的主机名,.NET Aspire的服务发现机制依赖内置的配置传递和服务名称解析,而非直接使用容器名或手动指定的主机名。以下是修正步骤:
移除Web项目中硬编码的连接字符串
删除appsettings.json里的PostgresConnection配置项,让Aspire自动注入正确的连接字符串。在Web项目中绑定Aspire数据库配置
确保Web项目已安装Aspire.Npgsql.EntityFrameworkCore.PostgreSQL包,然后在Program.cs中添加代码,通过Aspire的服务引用获取连接字符串:builder.AddNpgsqlDbContext<YourDbContext>("MyDatabase");这里的
"MyDatabase"必须和AppHost中AddDatabase("MyDatabase")的名称完全一致,Aspire会自动将Postgres服务的连接字符串注入到DbContext中。验证服务引用关系
AppHost中web.WithReference(postgres)已建立Web项目与Postgres服务的依赖关系,Aspire会自动处理服务发现和连接字符串传递,无需手动指定Host=Postgres。可选:手动获取连接字符串
如果不使用DbContext,也可以通过IConfiguration获取Aspire注入的连接字符串:var connectionString = builder.Configuration.GetConnectionString("MyDatabase");
在.NET Aspire环境中,服务运行在Aspire创建的专用网络中,服务名称的解析由Aspire的服务发现组件处理。手动硬编码Host=Postgres无法被Aspire的服务发现机制正确解析,而通过AddDatabase和WithReference的组合,Aspire会自动生成包含正确服务地址的连接字符串并注入到Web项目中。
内容的提问来源于stack exchange,提问作者Arash.Zandi

