Skip to content

Commit

Permalink
Don't use NpgsqlDataSource from DI if connection string/connection is…
Browse files Browse the repository at this point in the history
… specified (#3102)

Fixes #3060

(cherry picked from commit c0c962c)
  • Loading branch information
roji committed Feb 17, 2024
1 parent 47cac24 commit 44ed3f2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/EFCore.PG/Internal/NpgsqlSingletonOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ public virtual void Initialize(IDbContextOptions options)
// TODO: Remove after https://github.com/dotnet/efcore/pull/29950
ApplicationServiceProvider = coreOptions.ApplicationServiceProvider;

DataSource = npgsqlOptions.DataSource ?? coreOptions.ApplicationServiceProvider?.GetService<NpgsqlDataSource>();
DataSource = npgsqlOptions.DataSource ?? (npgsqlOptions.ConnectionString is null && npgsqlOptions.Connection is null
? coreOptions.ApplicationServiceProvider?.GetService<NpgsqlDataSource>()
: null);
}

/// <inheritdoc />
Expand Down
22 changes: 21 additions & 1 deletion test/EFCore.PG.Tests/NpgsqlRelationalConnectionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public void Uses_DbDataSource_from_DbContextOptions()
Assert.Equal("Host=FakeHost", connection2.ConnectionString);
}

[Fact]
[Fact(Skip = "Passes in isolation, but fails when the entire test suite is run because of #2891")]
public void Uses_DbDataSource_from_application_service_provider()
{
var serviceCollection = new ServiceCollection();
Expand Down Expand Up @@ -81,6 +81,26 @@ public void Uses_DbDataSource_from_application_service_provider()
Assert.Equal("Host=FakeHost", connection2.ConnectionString);
}

[Fact] // #3060
public void DbDataSource_from_application_service_provider_does_not_used_if_connection_string_is_specified()
{
var serviceCollection = new ServiceCollection();

serviceCollection
.AddNpgsqlDataSource("Host=FakeHost1")
.AddDbContext<FakeDbContext>(o => o.UseNpgsql("Host=FakeHost2"));

using var serviceProvider = serviceCollection.BuildServiceProvider();

using var scope1 = serviceProvider.CreateScope();
var context1 = scope1.ServiceProvider.GetRequiredService<FakeDbContext>();
var relationalConnection1 = (NpgsqlRelationalConnection)context1.GetService<IRelationalConnection>()!;
Assert.Null(relationalConnection1.DbDataSource);

var connection1 = context1.GetService<FakeDbContext>().Database.GetDbConnection();
Assert.Equal("Host=FakeHost2", connection1.ConnectionString);
}

[Fact]
public void Can_create_master_connection_with_connection_string()
{
Expand Down

0 comments on commit 44ed3f2

Please sign in to comment.