diff --git a/src/EFCore.Design/Design/Internal/DbContextOperations.cs b/src/EFCore.Design/Design/Internal/DbContextOperations.cs index 69dd87d7597..e2ca56f13ca 100644 --- a/src/EFCore.Design/Design/Internal/DbContextOperations.cs +++ b/src/EFCore.Design/Design/Internal/DbContextOperations.cs @@ -203,9 +203,9 @@ where i.IsGenericType { try { - return (DbContext)Activator.CreateInstance(context); + return (DbContext)ActivatorUtilities.GetServiceOrCreateInstance(appServices, context); } - catch (MissingMethodException ex) + catch (Exception ex) { throw new OperationException(DesignStrings.NoParameterlessConstructor(context.Name), ex); } diff --git a/test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs b/test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs index 0f2f60ddbc7..f12dd83a4cf 100644 --- a/test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs +++ b/test/EFCore.Design.Tests/Design/Internal/DbContextOperationsTest.cs @@ -18,6 +18,12 @@ public void CreateContext_gets_service() CreateOperations(typeof(TestProgram)).CreateContext(typeof(TestContext).FullName); } + [ConditionalFact] + public void CreateContext_gets_service_without_AddDbContext() + { + CreateOperations(typeof(TestProgramWithoutAddDbContext)).CreateContext(typeof(TestContext).FullName); + } + [ConditionalFact] public void GetContextInfo_returns_correct_info() { @@ -67,6 +73,20 @@ private static TestWebHost BuildWebHost(string[] args) => CreateWebHost(b => b.UseInMemoryDatabase("In-memory test database")); } + private static class TestProgramWithoutAddDbContext + { + private static TestWebHost BuildWebHost(string[] args) + => new TestWebHost( + new ServiceCollection() + .AddSingleton( + new TestContext( + new DbContextOptionsBuilder() + .UseInMemoryDatabase("In-memory test database") + .EnableServiceProviderCaching(false) + .Options)) + .BuildServiceProvider()); + } + private static class TestProgramRelational { private static TestWebHost BuildWebHost(string[] args)