You need to define IWebHost BuildWebHost(string[] args)
or IWebHostBuilder CreateWebHostBuilder(string[] args)
in Program
.
The method name matters (I had CreateWebHost
and it was failing).
For me, "Add an implementation of 'IDesignTimeDbContextFactory' to the project" was a red herring. It couldn't find my IWebHostBuilder
so it couldn't use the ServiceProvider
configured for my DbContext
. Using the accepted answer here might be valid for some people but violates DRY for me.
Using this answer I ran my migration in verbose mode: dotnet ef migrations add spottedmahn -v
:
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding IWebHost accessor...
No CreateWebHostBuilder(string[]) method was found on type 'MyApp.Web.Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'MyDBContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'MyDBContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time. ---> System.MissingMethodException: No parameterless constructor defined for this object.
I then noticed "No CreateWebHostBuilder found...". After some experimentation I learned either of these code segments are valid.
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
or
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
The doc page only refers to the BuildWebHost
method but the verbose log refers it refers to the CreateWebHostBuilder
method. ♂️