ASP.NET Core framework gives us two well defined places for initialization:
1. the Startup.ConfigureServices()
method for registering DI services
2. the Startup.Configure()
method for configuration of middleware pipeline
But what about other initialization steps specific to my web application? Where should those go, especially if they have dependencies that need to be injected?
For example I need to initialize database ORM based on connection string which is specified in configuration file appsettings.json. So this initialization code has dependency on IConfiguration
and perhaps other custom services that are registered into DI container during Startup.ConfigureServices()
So as per recommendations from these articles:
https://odetocode.com/blogs/scott/archive/2019/02/14/net-core-opinion-7-startup-responsibilities.aspx
https://odetocode.com/blogs/scott/archive/2019/03/07/net-core-opinion-10-move-more-code-out-of.aspx
I tried to encapsulate initialization logic in separate classes and then to create extension method for IWebHostBuilder
that would execute this code, but how can I make framework inject IConfiguration
and other custom dependencies into this extension methods? Also, can I be sure that this code will be executed after Startup.ConfigureServices()
when all dependencies are registered?
Is there some better or recommended way to perform this kind of tasks?
In ASP.NET Core, the Startup class provides the entry point for an application, and is required for all applications.
The startup class contains two methods: ConfigureServices and Configure. Declaration of this method is not mandatory in startup class. This method is used to configure services that are used by the application. When the application is requested for the first time, it calls ConfigureServices method.
The appsettings. json file is generally used to store the application configuration settings such as database connection strings, any application scope global variables, and much other information.
ConfigureServices() takes a parameter of type IServiceCollection. Configure() takes a parameter of type IApplicationBuilder with possible parameters of any Service which is registered in the ConfigureServices() method. an application should contain an ConfigureServices() method with an optional Configure() method.
You can add an extension method for IWebHost
(instead of IWebHostBuilder
) and then use IWebHost.Services
for resolving services. Here's an example of how to retrieve IConfiguration
:
public static class WebHostExtensions
{
public static IWebHost SomeExtension(this IWebHost webHost)
{
var config = webHost.Services.GetService<IConfiguration>();
// Your initialisation code here.
// ...
return webHost;
}
}
Usage of this extension method would look something like this:
CreateWebHostBuilder(args)
.Build()
.SomeExtension()
.Run();
If you need an async
version of SomeExtension
, you can split up the chaining above and await
the extension method. Here's what that might look like:
public static async Task SomeExtensionAsync(this IWebHost webHost)
{
var config = webHost.Services.GetService<IConfiguration>();
// Your initialisation code here with awaits.
// ...
}
Usage looks something like this:
public static async Task Main(string[] args)
{
var webHost = CreateWebHostBuilder(args)
.Build();
await webHost.SomeExtensionAsync();
webHost.Run();
}
Also, can I be sure that this code will be executed after
Startup.ConfigureServices()
when all dependencies are registered?
With the approach I've outlined above, the answer here is yes.
Note that IWebHost.Services
represents the root IServiceProvider
, which will not support resolving scoped instances. IConfiguration
is a singleton, so this isn't an issue for that, but if you have scoped dependencies, you'll need to create an explicit scope inside of your extension method.
In Program.cs
you have the following code for your Main
method:
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
After the Build()
part has run, you have a fully configured host. As such, you can simply do something like the following:
var host = CreateWebHostBuilder(args).Build();
// do something with host
host.Run();
The host has a member, Services
, which is an instance of IServiceProvider
, so you can pull any services you need from that, i.e.
var config = host.Services.GetRequiredService<IConfiguration>();
Just bear in mind that at this point, there is no inherent scope, so if you need scoped services, you'll need to create one:
using (var scope = host.Services.CreateScope())
{
var myScopedService = scope.ServiceProvider.GetRequiredService<MyScopedService>();
// do something with myScopedService
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With