BuildWebHost – Unable to create an object of type ApplicationDbContext error in EF Core 2.x – How to Fix

BuildWebHost - Unable to create an object of type ApplicationDbContext error in EF Core 2.x - How to Fix

A couple days ago I had to fix a EF Core issue experienced to one of my readers when he was working on the EF Core Migrations (Chapter 4 of ASP.NET Core 2 and Angular 5 book). This was the error, as reported on GitHub:

An error occurred while calling method ‘BuildWebHost’ on class ‘Program’. Continuing without the application service provider.
Unable to create an object of type ‘ApplicationDbContext’. Add an implementation of ‘IDesignTimeDbContextFactory’ to
the project, or see for additional patterns supported at design time.

The issue

After some research through the official docs and similar issues I’ve seen that it was mostly due to the fact that they changed the behaviour of how the BuildWebHost method – which is invoked in the   file to obtain the application services – works: now it invokes the Configure method in the   file, which could lead to unexpected problems if that method contains some database initialization code. The major issue there is that such “problems” will most likely raise misleading exceptions whenever the seeding code runs before the first   /   command execution – when the database doesn’t yet exist.

The fix

Luckily enough, fixing that is just as easy as following the official EF Core 1.x to 2.x migration guide:

  • Remove all the DB initialization code from the Startup.cs file’s   method.
  • Put it into the Program.cs file’s   method, in the following way:
That’s about it!

If you want to know more about .NET Core and Angular check out the ASP.NET Core 2 and Angular 5 book, available in paperback and/or digital format. Promo Code: ASPCA50 to get it with a 50% discount!



About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

Leave a Reply

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.