There is actually a default pattern that you can employ to achieve this result without having to implement IDesignTimeDbContextFactory
and do any config file copying.
It is detailed in this doc, which also discusses the other ways in which the framework will attempt to instantiate your DbContext
at design time.
Specifically, you leverage a new hook, in this case a static method of the form public static IWebHost BuildWebHost(string[] args)
. The documentation implies otherwise, but this method can live in whichever class houses your entry point (see src). Implementing this is part of the guidance in the 1.x to 2.x migration document and what's not completely obvious looking at the code is that the call to WebHost.CreateDefaultBuilder(args)
is, among other things, connecting your configuration in the default pattern that new projects start with. That's all you need to get the configuration to be used by the design time services like migrations.
Here's more detail on what's going on deep down in there:
While adding a migration, when the framework attempts to create your DbContext
, it first adds any IDesignTimeDbContextFactory
implementations it finds to a collection of factory methods that can be used to create your context, then it gets your configured services via the static hook discussed earlier and looks for any context types registered with a DbContextOptions
(which happens in your Startup.ConfigureServices
when you use AddDbContext
or AddDbContextPool
) and adds those factories. Finally, it looks through the assembly for any DbContext
derived classes and creates a factory method that just calls Activator.CreateInstance
as a final hail mary.
The order of precedence that the framework uses is the same as above. Thus, if you have IDesignTimeDbContextFactory
implemented, it will override the hook mentioned above. For most common scenarios though, you won't need IDesignTimeDbContextFactory
.