Asp.Net core 2.0: determine the startup class invoked by migration or another ef operation

Currently, the entire default Startup.cs is executed for each db-related operation, for example, using dping, adding migration, updating db for migration, etc.

I have a heavy application-specific code in Startup that needs to be called only if the application runs for real. So, how could I find that the Startup class is being launched from a migration or other command related to the dotnet database.

+5
source share
2 answers

Well, as noted in the comment on the question, there is an IDesignTimeDbContextFactory interface that needs to be implemented to resolve DbContext during development.

It might look something like this:

 public static class Programm{ ... public static IWebHost BuildWebHostDuringGen(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseStartup<StartupGen>() // <--- I'm just using different Startup child there where could be less complex code .UseDefaultServiceProvider(options => options.ValidateScopes = false).Build(); } } public class DbContextFactory : IDesignTimeDbContextFactory<MyDbContext> { public MyDbContex CreateDbContext(string[] args) { return Program.BuildWebHostDuringGen(args).Services.GetRequiredService<MyDbContext>(); } } 

However, due to some unclear reasons (I asked the guys from Microsoft, but they don’t explain it to me) dotnet currently implicitly calls Programm.BuildWebHost on each operation, even if it is closed, which is the reason the standard stream every time for the author of the question. A workaround for this is to Rename Programm.BuildWebHost to something else, such as InitWebHost

There is a problem created for this , so it may be resolved in version 2.1 in the future.

+4
source

The documentation is not yet clear why this is happening. I have not yet found a specific answer why Startup.Configure works. In 2.0, it is recommended to transfer any carry / seeding code to Program.Main . Here is an example of bricelam on github .

 public static IWebHost MigrateDatabase(this IWebHost webHost) { using (var scope = webHost.Services.CreateScope()) { var services = scope.ServiceProvider; try { var db = services.GetRequiredService<ApplicationDbContext>(); db.Database.Migrate(); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred while migrating the database."); } } return webHost; } public static void Main(string[] args) { BuildWebHost(args) .MigrateDatabase() .Run(); } 
+2
source

Source: https://habr.com/ru/post/1270890/


All Articles