Over a million developers have joined DZone.

ASP.NET Core: Environment-based Configuring Methods

DZone's Guide to

ASP.NET Core: Environment-based Configuring Methods

Environments are often a key part of the development process. In this post we take a look at how to take advantage of environment-based configurations in ASP.NET Core.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

A fancy thing that ASP.NET Core supports is environment-based application configuring at code level. We can write special methods in an application start-up class and use default ones as fallbacks. This blog post shows how to write environment based configuring methods on ASP.NET Core.

Default Configuring Methods of Start-Up Class

When we create a new ASP.NET Core application, our Startup class looks like this.

public class Startup
    public Startup(IHostingEnvironment env)
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        Configuration = builder.Build();
    }public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
        // Add framework services.
    }       // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        loggerFactory.AddDebug();if (env.IsDevelopment())
        }           app.UseStaticFiles();

        app.UseMvc(routes =>
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

The ConfigureServices() method adds services to the container, and the Configure() method configures the request pipeline.

Configuring Multiple Environments

It’s possible we need to configure our application based on the environment where the application is running. We may want to use some specific services and features in development mode and some others in release mode. One option is to use default configuring methods and #ifdef checks, but these make our code look ugly.

ASP.NET Core allows us to define special versions of configuring methods:

  • Configure<ENVIRONMENT>Services()
  • Configure<ENVIRONMENT>()

<ENVIRONMENT> is the name of the environment where the application runs. For example, with debug builds, we can use Development as the environment name. It gives us the following two methods:

  • ConfigureDevelopmentServices()
  • ConfigureDevelopment()

In the same way, we can use Staging and Production as environment names. We can try out these methods with some lines of additional code.

public void ConfigureDevelopmentServices(IServiceCollection services)
public void ConfigureDevelopment(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    Configure(app, env, loggerFactory);

We can run the application and check the output in the debug window, or we can just use breakpoints to see if the application is stopping on these when we run it.

Adding Custom Environments

It’s possible we need support for additional environments. Behind the curtains, ASP.NET Core uses the ASPNETCORE_ENVIRONMENT environment variable to find out what type of environment it is currently running in. We can set a value to this variable on the Debug settings page of project properties.

ASPNETCORE_ENVIRONMENT variable on project properties page

And methods for environment called “Custom” are here:

public void ConfigureCustomServices(IServiceCollection services)

public void ConfigureCustom(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    Configure(app, env, loggerFactory);

This way we can add methods for as many environments as we want.

Wrapping Up

We can write configuration methods based on the environment name and use default ones as fallbacks for other environments. This way we can avoid ugly code that has to go through several environment name checks. The environment name is held in the ASPNETCORE_ENVIRONMENT variable, and the value can be set on the project properties page. Using environment based configuration methods we can keep our code cleaner.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

environment ,configuration ,asp.net core ,web dev

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}