diff --git a/src/EFCore/Internal/DbContextPool.cs b/src/EFCore/Internal/DbContextPool.cs index b0472c0ee67..83cc7fecd25 100644 --- a/src/EFCore/Internal/DbContextPool.cs +++ b/src/EFCore/Internal/DbContextPool.cs @@ -51,7 +51,8 @@ public DbContextPool(DbContextOptions options) private static Func CreateActivator(DbContextOptions options) { - var constructors = typeof(TContext).GetTypeInfo().DeclaredConstructors.Where(c => !c.IsStatic && c.IsPublic).ToArray(); + var constructors = typeof(TContext).GetTypeInfo().DeclaredConstructors + .Where(c => !c.IsStatic && c.IsPublic && c.GetParameters().Length > 0).ToArray(); if (constructors.Length == 1) { diff --git a/test/EFCore.SqlServer.FunctionalTests/DbContextPoolingTest.cs b/test/EFCore.SqlServer.FunctionalTests/DbContextPoolingTest.cs index 0212257e1c8..3a810311b89 100644 --- a/test/EFCore.SqlServer.FunctionalTests/DbContextPoolingTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/DbContextPoolingTest.cs @@ -446,6 +446,50 @@ public WrongParameterConstructorContext(string x) } } + [ConditionalFact] + public void Does_not_throw_when_parameterless_and_correct_constructor() + { + var serviceProvider + = new ServiceCollection().AddDbContextPool(_ => { }) + .BuildServiceProvider(validateScopes: true); + + using var scope = serviceProvider.CreateScope(); + + var context = scope.ServiceProvider.GetRequiredService(); + + Assert.Equal("Options", context.ConstructorUsed); + } + + [ConditionalFact] + public void Does_not_throw_when_parameterless_and_correct_constructor_using_factory_pool() + { + var serviceProvider + = new ServiceCollection().AddPooledDbContextFactory(_ => { }) + .BuildServiceProvider(validateScopes: true); + + using var scope = serviceProvider.CreateScope(); + + var factory = scope.ServiceProvider.GetRequiredService>(); + using var context = factory.CreateDbContext(); + + Assert.Equal("Options", context.ConstructorUsed); + } + private class WithParameterlessConstructorContext : DbContext + { + public string ConstructorUsed { get; set; } + + public WithParameterlessConstructorContext() + { + ConstructorUsed = "Parameterless"; + } + + public WithParameterlessConstructorContext(DbContextOptions options) + : base(options) + { + ConstructorUsed = "Options"; + } + } + [ConditionalTheory] [InlineData(false, false)] [InlineData(true, false)]