Unable to create an object of type ‘ApplicationDbContext’. Add an implementation of ‘IDesignTimeDbContextFactory

Forgive the long title, but this is an issue I have been fighting trying to upgrade an Identity Server 4 project to ASP.NET Core 2. There is an issue on GitHub dedicated to this exact error which can be found here. Before you go down the route of trying all the suggestions in the issue take a moment and make sure that nothing in the Startup class is doing anything that would try to hit the database with Entity Framework.

There is a nice section in the official migration docs titled “Move database initialization code” which I seemed to have missed. So before you head down any rabbit holes like I did make sure this isn’t what is causing your need to add an implementation of IdesignTimeDbContextFactory.

As stated in the migration docs move database related code out of the Configure function of the Startup class and into the Main function. The following is the example of this from the docs.

var host = BuildWebHost(args);

using (var scope = host.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    try
    {
        // Requires using RazorPagesMovie.Models;
        SeedData.Initialize(services);
    }
    catch (Exception ex)
    {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "An error occurred seeding the DB.");
    }
}

host.Run();

This will keep Entity Framework tooling from accidentally running code you didn’t expect.  With version 2 all the code in the Configure function gets run.


Also published on Medium.

12 thoughts on “Unable to create an object of type ‘ApplicationDbContext’. Add an implementation of ‘IDesignTimeDbContextFactory<ApplicationDbContext>‘”

  1. Since this is the top Google result I’m also going to add that I got this error when I had 2 startup projects instead of 1. Going back to 1 fixed it, no idea why.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.