Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        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.
        services.AddMvc();
    }       // 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.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }           app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                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)
{
    Debug.WriteLine("ConfigureDevelopmentServices");
    ConfigureServices(services);
}
public void ConfigureDevelopment(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    Debug.WriteLine("ConfigureDevelopment");
    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)
{
    Debug.WriteLine("ConfigureCustomServices");
    ConfigureServices(services);
}

public void ConfigureCustom(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    Debug.WriteLine("ConfigureCustom");
    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.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
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 DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}