Skip to content

DbContextFactory could be more tolerant of there being multiple constructors on a DbContext #24124

Closed

Description

When creating a DbContext we often have one constructor that accepts DbContextOptions and another no-arg constructor so the DbContext will work with the EF tooling for creating migrations. However, when using DbContextFactory having more than one constructor on the DbContext results in the factory being unable to create a new DbContext and results in an exception

System.InvalidOperationException
Multiple constructors accepting all given argument types have been found in type

This is due to the implementation of DbContextFactorySource that mandates a single public non-static constructor

if (constructors.Length == 1)

Although there are work-arounds available with regards to the EF core tooling (https://docs.microsoft.com/en-gb/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli) it would be great if these were not required just because we are using DbContextFactory.


The DbContextFactorySource could be changed so the first 'if' statement is replaced with a for-each loop, iterating over each candidate constructor. The rest of the code inside the existing if statement is already checking parameter count and parameter types, so the for-each change would still allow the DbContextFactorySource to find the constructor that accepted DbContextOptions, but ignore any other constructors that may be present on the DbContext

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions