How do I dynamically choose a connection string based on Environment in .Net Core startup?
<p>In the StartUp class's Configure method of ASP.Net MVC Core, "IHostingEnvironment env" is passed in via Dependency Injection.
And decisions can be made based on the environment. For example,</p>

<pre><code>        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
</code></pre>

<p>In ConfigureServices, I want to do something like this to pick the correct Connection string.
Something like:</p>

<pre><code>        if (env.IsDevelopment())
        {
            services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }
        else if (env.IsStaging())
        {
            // Add Staging Connection
        }
        else
        {
            // Add Prod Connection
        }
</code></pre>

<p>But "IHostingEnvironment env" is not passed in to the ConfigureServices method by default.
So I modify the signature from:</p>

<pre><code>public void ConfigureServices(IServiceCollection services)
</code></pre>

<p>to</p>

<pre><code>public void ConfigureServices(IServiceCollection services, IHostingEnvironment env)
</code></pre>

<p>and in ConfigureServices put:</p>

<pre><code>        if (env.IsDevelopment())
        {
            services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }
        else if (env.IsStaging())
        {
            // Add Staging Connection
        }
        else
        {
            // Add Prod Connection
        }
</code></pre>

<p>So now when I run I get this error message:</p>

<p>"The ConfigureServices method must either be parameterless or take only one parameter of type IServiceCollection."</p>

<p>ConfigureServices() won't take in the IHostingEnvironment var.</p>

<p>But "Startup.StartUp(IHostingEnvironment env)" does.
I thought about adding a StartUp class field and setting it to the correct environment from Startup() and then using that field to make the decision flow in ConfigureServices.  But this seems like a hack.</p>

<p>I know environment is a first class concept in .Net Core.
Is there a way to do this straight from appsetting.json?</p>

<p>What is the best practice to accomplish this?</p>