Skip to content

Creating migration scripts fails since upgrade to .net5.0. Unable to create an object of type 'FailureContext' #23306

Closed as not planned

Description

@magahl

Issue

After upgrading to .net5.0 i can no longer create a migration script, since ef core complains on DbContext cannot be created even though it indeed have a parameterless constructor. My command for creating the script haven't changed only the tooling version. This may very well be me doing something wrong though :)

I have looked here for guidance without sucess: https://docs.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#using-a-constructor-with-no-parameters

Code

A minimal repo with the issue can be found here: https://github.com/magahl/EF.Coore.MigrationFailure

Im running the script from soultion root folder.

dotnet ef migrations script -p EF.Core.Failure/EF.Core.Failure.csproj -s EF.Core.Failure/EF.Core.Failure.csproj --output C:\temp\FailureMigrate.sql --context FailureContext  --idempotent

Error

PS C:\Code\EF.Core.Failure> dotnet ef migrations script -p EF.Core.Failure/EF.Core.Failure.csproj -s EF.Core.Failure/EF.Core.Failure.csproj --output C:\temp\FailureMigrate.sql --context FailureContext  --idempotent --verbose
Using project 'EF.Core.Failure/EF.Core.Failure.csproj'.
Using startup project 'EF.Core.Failure/EF.Core.Failure.csproj'.
Writing 'EF.Core.Failure\obj\EF.Core.Failure.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\magnu\AppData\Local\Temp\tmpEA31.tmp /verbosity:quiet /nologo EF.Core.Failure/EF.Core.Failure.csproj
Writing 'EF.Core.Failure\obj\EF.Core.Failure.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\magnu\AppData\Local\Temp\tmpEC55.tmp /verbosity:quiet /nologo EF.Core.Failure/EF.Core.Failure.csproj
Build started...
dotnet build EF.Core.Failure/EF.Core.Failure.csproj /verbosity:quiet /nologo

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:01.04
Build succeeded.
dotnet exec --depsfile C:\Code\EF.Core.Failure\EF.Core.Failure\bin\Debug\net5.0\EF.Core.Failure.deps.json --additionalprobingpath C:\Users\magnu\.nuget\packages --runtimeconfig C:\Code\EF.Core.Failure\EF.Core.Failure\bin\Debug\net5.0\EF.Core.Failure.runtimeconfig.json C:\Users\magnu\.dotnet\tools\.store\dotnet-ef\5.0.0\dotnet-ef\5.0.0\tools\netcoreapp3.1\any\tools\netcoreapp2.0\any\ef.dll migrations script --output C:\temp\FailureMigrate.sql --context FailureContext --idempotent --assembly C:\Code\EF.Core.Failure\EF.Core.Failure\bin\Debug\net5.0\EF.Core.Failure.dll --startup-assembly C:\Code\EF.Core.Failure\EF.Core.Failure\bin\Debug\net5.0\EF.Core.Failure.dll --project-dir C:\Code\EF.Core.Failure\EF.Core.Failure\ --language C# --working-dir C:\Code\EF.Core.Failure --verbose --root-namespace EF.Core.Failure
Using assembly 'EF.Core.Failure'.
Using startup assembly 'EF.Core.Failure'.
Using application base 'C:\Code\EF.Core.Failure\EF.Core.Failure\bin\Debug\net5.0'.
Using working directory 'C:\Code\EF.Core.Failure\EF.Core.Failure'.
Using root namespace 'EF.Core.Failure'.
Using project directory 'C:\Code\EF.Core.Failure\EF.Core.Failure\'.
Remaining arguments: .
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider in assembly 'EF.Core.Failure'...
Finding Microsoft.Extensions.Hosting service provider...
No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'FailureContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'FailureContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[EF.Core.Failure.FailureContext]' while attempting to activate 'EF.Core.Failure.FailureContext'.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.ScriptMigration(String fromMigration, String toMigration, MigrationsSqlGenerationOptions options, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScriptMigrationImpl(String fromMigration, String toMigration, Boolean idempotent, Boolean noTransactions, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScriptMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'FailureContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

EF Core version: 5.0.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: Net 5.0
Operating system: Windows 20H2
IDE: n/a
Entity Framework Core .NET Command-line Tools: 5.0.0

Activity

  1. changed the title [-]Creating migration scripts fails since upgrade to .net5.0, unable to create type of 'Context'[/-] [+]Creating migration scripts fails since upgrade to .net5.0. Unable to create an object of type 'FailureContext'[/+] on Nov 13, 2020
  2. ajcvickers commented on Nov 13, 2020

    @ajcvickers
    Contributor

    @bricelam This repros for me. In 3.1, we find the DbContext, in 5.0 we don't for the same project. Using the 5.0 tool and SDK in both cases.

  3. added this to the 5.0.1 milestone on Nov 13, 2020
  4. bricelam commented on Nov 16, 2020

    @bricelam
    Contributor

    Possibly introduced by PR #17273

  5. bricelam commented on Nov 19, 2020

    @bricelam
    Contributor

    @ajcvickers I'm not sure if this is our bug or DI's. If you change the order of the constructors (and presumably the Reflection order) it works....

    We could work around it, but I think we should probably get clarity on the expected behavior first.

  6. removed this from the 5.0.1 milestone on Nov 19, 2020
  7. ajcvickers commented on Nov 19, 2020

    @ajcvickers
    Contributor

    @bricelam Did D.I. behavior change between 3.1 and 5.0?

  8. bricelam commented on Nov 20, 2020

    @bricelam
    Contributor

    No--we just started using DI to instantiate/activate DbContext types in 5.0

  9. bricelam commented on Nov 20, 2020

    @bricelam
    Contributor

    Possible outcomes:

    1. It's never supposed to throw in DI, and they fix it a 5.0 patch
    2. It's always supposed to throw in DI, and we add additional code to handle the exception in a 5.0 patch
    3. The behavior is undefined in DI, and we add code to handle the possible exception
  10. ajcvickers commented on Nov 22, 2020

    @ajcvickers
    Contributor

    @bricelam I did some more investigation into the D.I. behaviors. What happens seems to be dependent on whether or not the DbContext is registered in the D.I. container or not.

    Using this context:

    public class FailureContext : DbContext
    {
        public FailureContext(ILogger<FailureContext> logger)
        {
            Console.WriteLine($"With logger {logger}");
        }
    
        public FailureContext()
        {
            Console.WriteLine("Parameterless");
        }
    }

    This works for both GetService<FailureContext> and ActivatorUtilities.GetServiceOrCreateInstance<FailureContext> when both these types are in D.I.:

            var serviceProvider1 = new ServiceCollection()
                .AddSingleton<ILogger<FailureContext>, MyLogger>()
                .AddSingleton<FailureContext>()
                .BuildServiceProvider();
    
            var context1 = serviceProvider1.GetService<FailureContext>();
    
            var serviceProvider2 = new ServiceCollection()
                .AddSingleton<ILogger<FailureContext>, MyLogger>()
                .AddSingleton<FailureContext>()
                .BuildServiceProvider();
    
            var context2 = ActivatorUtilities.GetServiceOrCreateInstance<FailureContext>(serviceProvider2);

    Output:

    With logger MyLogger
    With logger MyLogger
    

    It also works if only DbContext is registered in D.I.:

            var serviceProvider1 = new ServiceCollection()
                //.AddSingleton<ILogger<FailureContext>, MyLogger>()
                .AddSingleton<FailureContext>()
                .BuildServiceProvider();
    
            var context1 = serviceProvider1.GetService<FailureContext>();
    
            var serviceProvider2 = new ServiceCollection()
                //.AddSingleton<ILogger<FailureContext>, MyLogger>()
                .AddSingleton<FailureContext>()
                .BuildServiceProvider();
    
            var context2 = ActivatorUtilities.GetServiceOrCreateInstance<FailureContext>(serviceProvider2);

    In this case the output shows that the parameterless constructor is used:

    Parameterless
    Parameterless
    

    It also works if FailureContext is not registered in D.I., but the logger is:

            var serviceProvider1 = new ServiceCollection()
                .AddSingleton<ILogger<FailureContext>, MyLogger>()
                //.AddSingleton<FailureContext>()
                .BuildServiceProvider();
    
            var context1 = serviceProvider1.GetService<FailureContext>();
    
            var serviceProvider2 = new ServiceCollection()
                .AddSingleton<ILogger<FailureContext>, MyLogger>()
                //.AddSingleton<FailureContext>()
                .BuildServiceProvider();
    
            var context2 = ActivatorUtilities.GetServiceOrCreateInstance<FailureContext>(serviceProvider2);

    In this case GetService returns null, but GetServiceOrCreateInstance still chooses the correct constructor.

    With logger MyLogger
    

    When this fails is when neither the logger or the logger are registered in D..I:

            var serviceProvider1 = new ServiceCollection()
                //.AddSingleton<ILogger<FailureContext>, MyLogger>()
                //.AddSingleton<FailureContext>()
                .BuildServiceProvider();
    
            var context1 = serviceProvider1.GetService<FailureContext>();
    
            var serviceProvider2 = new ServiceCollection()
                //.AddSingleton<ILogger<FailureContext>, MyLogger>()
                //.AddSingleton<FailureContext>()
                .BuildServiceProvider();
    
            var context2 = ActivatorUtilities.GetServiceOrCreateInstance<FailureContext>(serviceProvider2);
    Unhandled exception. System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[FailureContext]' while attempting to activate 'FailureContext'.
       at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
       at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
       at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance[T](IServiceProvider provider)
       at Program.Main(String[] args) in /home/ajcvickers/AllTogetherNow/FiveOh/Program.cs:line 155
    

    Based on this it seems like is quite a corner case. Any time the DbContext is registered in D.I., then this will work. Likewise, anytime, ILogger<> is registered in D.I., then this will work. So I don't think we should rush to patch this.

    @davidfowl Is this a bug in D.I., or is the defined behavior of GetServiceOrCreateInstance supposed to be constructor-order dependent in this case? If so, why?

  11. davidfowl commented on Nov 23, 2020

    @davidfowl
    Member

    @davidfowl Is this a bug in D.I., or is the defined behavior of GetServiceOrCreateInstance supposed to be constructor-order dependent in this case? If so, why?

    This feels like a bug to me, specifically that ActivatorUtilities.CreateInstance doesn't take length into account when picking constructors. It might be a massive breaking change but that behavior surprised me, especially because Activator.CreateFactory throws on the same input.

  12. ajcvickers commented on Nov 23, 2020

    @ajcvickers
    Contributor

    @davidfowl It may not be a breaking change to fix if all we do is change the failure case (attempting to use a constructor that will never work) into a success case (we now call the constructor that does work.) Regardless, I filed for dotnet/runtime#45119 this and I'm going to close as external here.

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions