DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > ASP.NET Core: Environment-based Configuring Methods

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.

Gunnar Peipman user avatar by
Gunnar Peipman
·
Mar. 15, 17 · Web Dev Zone · Tutorial
Like (3)
Save
Tweet
6.96K Views

Join the DZone community and get the full member experience.

Join For Free

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.

ASP.NET Core ASP.NET application

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Are All Kubernetes Ingresses the Same?
  • Caching Across Layers in Software Architecture
  • How to Build a Simple CLI With Oclif
  • Writing Beautiful, Optimized, and Better .NET Code With NDepend Static Analysis

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo