Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does IHostingEnvironment.EnvironmentName work?

In a .NET Core console application, if I add the following line...

IHostingEnvironment env = new HostingEnvironment();
Console.WriteLine(env.EnvironmentName);

I get this result...

Production

But when I do the same thing in an ASP.NET Core application on the same machine...

public Startup(IHostingEnvironment env)
{
    Debug.WriteLine(env.EnvironmentName);
}

I get this result...

Development

  • How exactly does EnvironmentName work?
  • How can I specify that my local machine is a Development environment?
  • How can I specify that Azure is a Production environment?

As an extra point, can EnvironmentName be configured to work with Debug and Release configurations within the solution?

enter image description here

  • Debug => Development
  • Release => Production

The ultimate goal is to be able to connect to a local SQL database when built using Debug, and an Azure database when built using Release.

like image 395
Matthew Layton Avatar asked Nov 09 '16 21:11

Matthew Layton


1 Answers

How exactly does EnvironmentName work?

.NET Core reads the name from an environmental variable.

How can I specify that my local machine is a Development environment?

Set the environmental variable to Development.

How can I specify that Azure is a Production environment?

Set the environmental variable to Production.

As an extra point, can EnvironmentName be configured to work with Debug and Release configurations within the solution?

You can create a launch profile that sets the environment name and use that profile with either Debug or Release configuration. The launch profile impacts the EnvironmentName when you launch from Visual Studio; you will need to use other means to set it, when you run the app in other environments.

The image below shows running the application in Release configuration and a MyDevProfile that sets EnvironmentName to Development.

enter image description here

like image 93
Shaun Luttin Avatar answered Oct 16 '22 03:10

Shaun Luttin