Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IWebHostBuilder.Configure() not executing in ASP.NET Core

Why is that a call to IWebHostBuilder.Configure() extension method seemingly doesn't do anything in ASP.NET Core (experienced in version 3.4.0)?

For example in this scenario:

public static IHostBuilder CreateHostBuilder(string[] args)
    => Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder => {
            webBuilder
                .UseSerilog( ... )

                .Configure(appBuilder => // Doesn't do anything.
                    appBuilder.UseSerilogRequestLogging( ... ))

                .UseStartup<Startup>();
        });

Here, UseSerilogRequestLogging() is called inside Configure() to add Serilog's request logging middleware before Startup executes, in order to place it at the beginning of the request pipeline, and also to keep logging-related configuration at one place.

But Configure() literally doesn't do anything, and the middleware is not added.

like image 698
Leaky Avatar asked Oct 29 '25 15:10

Leaky


1 Answers

The reason is that the IWebHostBuilder.Configure() method is not just a general configuration method. It actually registers the provided delegate as IStartup in the ServiceCollection. See source (albeit old) here.

This means that when UseStartup<Startup>() is called subsequently, it replaces the previously registered delegate, and thus the configuration in Configure() is not executed.

This behavior can be further confirmed if you place Configure() after UseStartup<>(). In this case, Configure() will be the one that replaces UseStartup<>(), and UseStartup() won't execute.

The documentation on Configure() method actually hints at this:

//
// Summary:
//     Specify the startup method to be used to configure the web application.
//

(Answered my own question, to spare some time for someone else who might end up being as perplexed as I was.)

like image 114
Leaky Avatar answered Oct 31 '25 12:10

Leaky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!