【问题标题】:Use MySQL in development and SQL Server in production在开发中使用 MySQL,在生产中使用 SQL Server
【发布时间】:2018-07-01 12:21:15
【问题描述】:

我想在本地计算机上使用 mysql,在生产服务器上使用 SQL Server。

这是我在Startup.cs 中尝试做的事情:

我有两种方法:

public void ConfigureServices(IServiceCollection services)
{
}

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

不幸的是,我必须在ConfigureServices 方法中加入这一行:

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

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

但是ConfigureServices 没有提供 env 参数,所以我无法测试:

if (env.IsDevelopment())

【问题讨论】:

  • env 设置为类中的一个字段,以便您访问它。可以在构造函数中设置
  • 您应该在本地和生产环境中使用相同的数据库供应商。否则基本行不通。您可以使用免费的SQL Server Express 或内置的LocalDB

标签: c# mysql sql-server entity-framework-core asp.net-core-2.0


【解决方案1】:

将托管环境注入启动并设置为类中的字段/属性,以便您访问它。

参考Application startup in ASP.NET Core

Startup 类构造函数接受主机定义的依赖项。 Startup 类中的一个常见的依赖注入用法是注入 IHostingEnvironment 以通过环境配置服务:

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("...");
        }
    }
}

链接中还提供了一个替代选项,您可以在其中使用基于约定的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-28
    • 2011-04-29
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多