EntityFramework.Docs icon indicating copy to clipboard operation
EntityFramework.Docs copied to clipboard

How is DbContext resolved at design-time in new ASP.NET Core projects?

Open aradalvand opened this issue 2 years ago • 2 comments

The Design-time DbContext Creation article in the docs explains how some EF Core Tools commands need to instantiate the application's DbContext in order to gather certain information, and that in ASP.NET Core projects, this is done by calling Program.CreateHostBuilder() to build the DI container, and then requesting the DbContext from the container.

This makes sense, except that it's been quite a while since ASP.NET Core projects no longer have a Program.CreateHostBuilder(), Startup.cs, etc. and all that code is now "flattened", if you will, inside Program.cs.

So, I was wondering how EF accomplishes the same thing now in this new structure? Does it, for example, execute everything in Program.cs up until app.Build(), or some sort of logic like that?

It would also be nice if the documentation I linked to could be updated to reflect this change in ASP.NET Core.

aradalvand avatar Aug 12 '23 05:08 aradalvand

In the new ASP.NET structure, the EF core tools are embedded in the program.cs file and it's being executed before the app.build

That is why every logic, customization or middlware should be put before the app.build section

Idoldev1 avatar Aug 23 '23 08:08 Idoldev1

The simple answer: Pure magic.

The gory details:

We call the entry point (Program.Main) and inject a custom diagnostics listener. This listener observes the host being built and captures the service provider then aborts execution by throwing an exception before the server is actually started.

bricelam avatar Aug 28 '23 21:08 bricelam