Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I perform custom application initialization steps in ASP.NET Core?

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?

like image 847
mlst Avatar asked Apr 16 '19 12:04

mlst


People also ask

What is the entry point for the application in ASP.NET Core?

In ASP.NET Core, the Startup class provides the entry point for an application, and is required for all applications.

Which method of startup class configures or adds services required by the application?

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.

What is Appsetting JSON in ASP.NET Core?

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.

What is difference between configure and ConfigureServices in .NET Core?

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.


Video Answer


2 Answers

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.

like image 78
Kirk Larkin Avatar answered Sep 18 '22 05:09

Kirk Larkin


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
}
like image 32
Chris Pratt Avatar answered Sep 18 '22 05:09

Chris Pratt