You are currently viewing How To Create Environment Specific Startup Methods In .NET Applications

How To Create Environment Specific Startup Methods In .NET Applications

In previous article, we have seen how to create environment specific Startup classes. This article is just extension to it. In this article, let’s have a look at how can we write environment specific methods in Startup class of .NET web applications.

Startup Class Methods

Startup class bootstraps the .NET application. It defines the request processing pipeline, DI configurations, and many other things.

Every startup class has two methods:

  • ConfigureServices, this is optional method. This is used to configure application’s services. A service is anything that provides functionality to the application. Services are registered in this method. These registered services are then consumed in the application via Dependency Injection or Application Services.
  • Configure, this method should always be present in the Startup class. This method defines application’s request pipeline.

Why to choose environment specific methods?

At first look, the idea of having environment specific startup classes, is almost same as the idea of having environment specific startup methods.

In my opinion, environment specific methods is just another way of organizing the code. This approach of environment specific methods might probably be helpful in case only one of the two Startup methods are different on different environments.

How does it work ?

The two methods of startup class can have environment specific versions by adding environment name, Configure{Enviroment} or Configure{Environment}Services.

For example, Configure method can have ConfigureProduction version for production environment. Also, ConfigureServices can have ConfigureProductionServices.

Below is the invocation logic for such methods:

  • If the method Configure{Environment}Services or Configure{Environment} is found, then it is used.
  • If such method is not found, then the methods with default names are called.

Below snippet shows the sample startup class. It has specific ConfigureServicesProduction method for production environments. The other environments will use the regular ConfigureServices method.

Again, you might not need this typically and you should always weigh the pros and cons of having environment specific code, especially from maintainability and testability perspectives. I hope this information was useful for you. Let me know your thoughts.

Leave a ReplyCancel reply

This Post Has One Comment