Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom environments in Asp.Net Core 2.0

I want to support more than the built-in "Development", "Staging", and "Production" environments that are defined in Microsoft.AspNetCore.Hosting.EnvironmentName. I realize that I'm free to invent whatever names I wish when setting the environment during program initialization, but that's not the problem. There are 3 extension methods defined in Microsoft.AspNetCore.Hosting.HostingEnvironmentExtensions that are used seemingly everywhere: IsDevelopment(), IsStaging(), and IsProduction().

How do you customize the behavior of IsDevelopment() so that multiple custom environment names each return true?

For example, I want to differentiate between local development and remote development; 2 environments with their own configuration settings, but both are considered "Development". Another example could be multiple "Staging" environments; one meant for internal testing, one meant for external/client testing, but both are considered "Staging".

I don't believe I can write my own IsDevelopment() extension method and safely assure that mine is always favored over Microsoft's (Closer is better). E.g. mine may be used by code in my project, but what about when code in Mvc itself calls it?

like image 206
Granger Avatar asked Sep 02 '25 14:09

Granger


1 Answers

There is presently no way to do it, due to the existence and usage of the 3 IsDevelopment(), IsStaging(), and IsProduction() extension methods.

What I've basically ended up doing is defining my own custom environments, and provided a mapping from each back to the 3 defined in Asp.Net Core.

In Main(), I create an instance of my specialized configuration class; it figures out what custom environment the code's running in. Then, when I call WebHostBuilder.UseEnvironment(), I use a property from that class which indicates the Asp.Net Core environment that corresponds to my custom one. And, finally, I inject my class (singleton) into the DI container so it can be used as needed.

like image 121
Granger Avatar answered Sep 05 '25 15:09

Granger