If you have to deal with a large number of hosting environments, configuring all of them in the Startup class can become messy. In the following sections, I will describe different ways that the Startup class can be used for complex configurations. You can find the source code of the following demo on GitHub.
The default configuration for the application performed by the Program class looks for JSON configuration files that are specific to the hosting environment being used to run the application. A file called appsettings.production.json can be used to store settings that are specific to the production platform.
When you load configuration data from a platform-specific file, the configuration settings it contains override any existing data with the same names. The appsettings.json file will be loaded when the application starts, followed by the appsettings.development.json file if the application is running in a development environment.
Selecting different configuration data files can be useful but doesn’t provide a complete solution for complex configurations because data files don’t contain C# statements. If you want to vary the configuration statements used to create services or register middleware components, then you can use different methods, where the name of the method includes the hosting environment:
When ASP.NET Core looks for the ConfigureServices and Configure methods in the Startup class, it first checks to see whether there are methods that include the name of the hosting environment. You can define separate methods for each of the environments that you need to support and rely on the default methods being called if there are no environment-specific methods available. Note that the default methods are not called if there are environment-specific methods defined.
Using different methods means you don’t have to use if statements to check the hosting environment name, but it can result in large classes, which is a problem in itself. For especially complex configurations, the final progression is to create a different configuration class for each hosting environment. When ASP.NET looks for the Startup class, it first checks to see whether there is a class whose name includes the current hosting environment.
Rather than specifying a class, the UseStartup method is given the name of the assembly that it should use. When the application starts, ASP.NET will look for a class whose name includes the hosting environment, such as StartupDevelopment or StartupProduction, and fall back to using the regular Startup class if one does not exist.
In this post, I showed different approaches on how to handle the configuration of your application. You can use different files, different methods or even different classes, depending on how complex your configuration will be.