1

I want to work with mysql on my local computer and SQL Server on production server.

Here is what I've tried to do in Startup.cs:

I have two methods:

public void ConfigureServices(IServiceCollection services)
{
}

and

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
}

Unfortunately, I have to put one of this lines in ConfigureServices method:

services.AddDbContext<DbContext>(options => options.UseMySQL("..."));

or

services.AddDbContext<pluginwebContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

But ConfigureServices does not provide env parameter so I cannot test with:

if (env.IsDevelopment())
2
  • set env as a field in the class to give you access to it. it can be set in the constructor Commented Jan 22, 2018 at 19:57
  • 1
    You should you same database vendor locally and in production. Otherwise it basically won't work. You can use free SQL Server Express or built-in LocalDB Commented Jan 22, 2018 at 20:15

1 Answer 1

2

Inject the hosting environment into startup and set as a field/property in the class to give you access to it.

Reference Application startup in ASP.NET Core

The Startup class constructor accepts dependencies defined by the host. A common use of dependency injection into the Startup class is to inject IHostingEnvironment to configure services by environment:

public class Startup {
    public Startup(IHostingEnvironment env) {
        HostingEnvironment = env;
    }

    public IHostingEnvironment HostingEnvironment { get; private set; }

    public void ConfigureServices(IServiceCollection services) {
        if (HostingEnvironment.IsDevelopment()) {
            // Development configuration
            services.AddDbContext<DbContext>(options => options.UseMySQL("..."));
        } else {
            // Staging/Production configuration
            services.AddDbContext<pluginwebContext>(options => options.UseSqlServer("...");
        }
    }
}

There is also an alternative option provided in the link where you use a convention-based approach.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.