From 2b04835be994761ef6cb554ad3a91b16597228ce Mon Sep 17 00:00:00 2001 From: Andriy Svyryd Date: Fri, 8 Dec 2023 13:03:29 -0800 Subject: [PATCH] Allow the second DbContext to be registered to use nongeneric options This is important for Identity --- .../EntityFrameworkServiceCollectionExtensions.cs | 2 +- test/EFCore.Tests/DbContextTest.Services.cs | 15 ++++++++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/EFCore/Extensions/EntityFrameworkServiceCollectionExtensions.cs b/src/EFCore/Extensions/EntityFrameworkServiceCollectionExtensions.cs index efc26abcce2..8908bbc31f6 100644 --- a/src/EFCore/Extensions/EntityFrameworkServiceCollectionExtensions.cs +++ b/src/EFCore/Extensions/EntityFrameworkServiceCollectionExtensions.cs @@ -1134,7 +1134,7 @@ private static void AddCoreServices( CreateDbContextOptions, optionsLifetime)); - serviceCollection.TryAdd( + serviceCollection.Add( new ServiceDescriptor( typeof(DbContextOptions), CreateDbContextOptions, diff --git a/test/EFCore.Tests/DbContextTest.Services.cs b/test/EFCore.Tests/DbContextTest.Services.cs index bbf7a5f3ad4..63784a67ca1 100644 --- a/test/EFCore.Tests/DbContextTest.Services.cs +++ b/test/EFCore.Tests/DbContextTest.Services.cs @@ -4044,8 +4044,8 @@ public void Throws_when_wrong_DbContextOptions_used() public void Throws_when_adding_two_contexts_using_non_generic_options() { var appServiceProvider = new ServiceCollection() - .AddDbContext(b => b.UseInMemoryDatabase(Guid.NewGuid().ToString())) .AddDbContext(b => b.UseInMemoryDatabase(Guid.NewGuid().ToString())) + .AddDbContext(b => b.UseInMemoryDatabase(Guid.NewGuid().ToString())) .BuildServiceProvider(validateScopes: true); using var serviceScope = appServiceProvider @@ -4078,7 +4078,7 @@ public NonGenericOptions2(DbContextOptions options) } [ConditionalFact] - public void AddDbContext_adds_single_options_for_all_types() + public void AddDbContext_adds_options_for_all_types() { var services = new ServiceCollection() .AddSingleton(_ => new DbContextOptions()) @@ -4086,18 +4086,23 @@ public void AddDbContext_adds_single_options_for_all_types() .AddDbContext(optionsLifetime: ServiceLifetime.Singleton) .BuildServiceProvider(validateScopes: true); - Assert.Single(services.GetServices()); + Assert.Equal(3, services.GetServices().Count()); + Assert.Equal( + 2, services.GetServices() + .Select(o => o.ContextType) + .Distinct() + .Count()); } [ConditionalFact] - public void First_DbContextOptions_in_serviceCollection_selected() + public void Last_DbContextOptions_in_serviceCollection_selected() { var services = new ServiceCollection() .AddDbContext(optionsLifetime: ServiceLifetime.Singleton) .AddDbContext(optionsLifetime: ServiceLifetime.Singleton) .BuildServiceProvider(validateScopes: true); - Assert.Equal(typeof(NonGenericOptions1), services.GetService().ContextType); + Assert.Equal(typeof(NonGenericOptions2), services.GetService().ContextType); } [ConditionalFact]