I'm sure not the first one to run into this, but I couldn't find any good example patterns. When working with .Net Core 3 and newer and creating a web app we can use a Startup class
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
One nice feature about the Startup class is that it first calls ConfigureServices in which we can add things into the dependency injection container and then calls the Configure method which supports dependency injection (we can add arguments to the method to get instances of those classes registered with the container in ConfigureServices).
This is nice as it allows us to make setup and initialization calls that are only available after instantiation, and can save considerable code if the classes being instantiated have a chain of dependencies. The Configure method allows the infrastructure to chain up those dependences where we would have to do it ourselves in the ConfigureServices method.
When building console apps we don't have the option of a Startup class. We directly call ConfigureServices.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
...
})
Where is a good clean place to do work that would normally consider placing in the Startup.Configure method? I'm especially interested in where to place things you want to occur before the Hosted Services are started up (for example I have a class responding to database changes that needs subscriptions wired up and I want this to occur before any Hosted Services startup which may alter the database). So in other words I'm looking for an opportunity to leverage dependency injection before the Hosted Services are started.