Skip to content

Commit

Permalink
Allow parameterless constructor in addition to required constructor w…
Browse files Browse the repository at this point in the history
…hen using context pooling (#28708)
  • Loading branch information
ajcvickers authored Aug 15, 2022
1 parent 3291ff5 commit 9e8b938
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/EFCore/Internal/DbContextPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ public DbContextPool(DbContextOptions<TContext> options)

private static Func<DbContext> CreateActivator(DbContextOptions<TContext> 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)
{
Expand Down
44 changes: 44 additions & 0 deletions test/EFCore.SqlServer.FunctionalTests/DbContextPoolingTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,50 @@ public WrongParameterConstructorContext(string x)
}
}

[ConditionalFact]
public void Does_not_throw_when_parameterless_and_correct_constructor()
{
var serviceProvider
= new ServiceCollection().AddDbContextPool<WithParameterlessConstructorContext>(_ => { })
.BuildServiceProvider(validateScopes: true);

using var scope = serviceProvider.CreateScope();

var context = scope.ServiceProvider.GetRequiredService<WithParameterlessConstructorContext>();

Assert.Equal("Options", context.ConstructorUsed);
}

[ConditionalFact]
public void Does_not_throw_when_parameterless_and_correct_constructor_using_factory_pool()
{
var serviceProvider
= new ServiceCollection().AddPooledDbContextFactory<WithParameterlessConstructorContext>(_ => { })
.BuildServiceProvider(validateScopes: true);

using var scope = serviceProvider.CreateScope();

var factory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<WithParameterlessConstructorContext>>();
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<WithParameterlessConstructorContext> options)
: base(options)
{
ConstructorUsed = "Options";
}
}

[ConditionalTheory]
[InlineData(false, false)]
[InlineData(true, false)]
Expand Down

0 comments on commit 9e8b938

Please sign in to comment.