从appsettings.json获取ConnectionString,而不是在.NET Core 2.0 App中进行硬编码 [英] Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

查看:88
本文介绍了从appsettings.json获取ConnectionString,而不是在.NET Core 2.0 App中进行硬编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在NET Core2.0 App中有以下课程.

I have the following class in NET Core2.0 App.

// required when local database does not exist or was deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
{
    public AppContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<AppContext>();
        builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
        return new AppContext(builder.Options);
    }
}

在Core 2.0中,当数据库不存在时,这是迁移所必需的,并且必须在运行 update-database 时创建.
升级到ASP后无法创建迁移.NET Core 2.0

This is required in Core 2.0 with migration when Database does not exist and has to be created when you run update-database.
Unable to create migrations after upgrading to ASP.NET Core 2.0

我不想在2个地方(这里和appsettings.json中)拥有ConnectionString,而仅在.json中 所以我试图替换

I would like not having ConnectionString in 2 places(here and in appsettings.json) but only in .json so I have tried to replace

"Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"

使用

ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString

但是它不起作用,我得到的是空值.

but it's not working, I'm getting null value.

更新1:
只是要注意,在Core 2中不必显式添加.json,因此问题不在于文件.
https://andrewlock.net/探索程序并在asp-net-core-2-preview1-2/
中启动
更新2:
另外,我已经在使用Configuration将ConnectionString从.json发送到Context:

UPDATE 1:
Just to note that adding explicitly .json is not necessery in Core 2 so the problem is not with the file.
https://andrewlock.net/exploring-program-and-startup-in-asp-net-core-2-preview1-2/

UPDATE 2:
Also I am already using Configuration for sending ConnectionString from .json to Context:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<AppContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }
}

但是我不能将它用于 ToDoContextFactory ,因为它没有配置,并且 ToDoContextFactory 用于迁移,因此该应用程序根本无法运行.

But I can not use this for ToDoContextFactory because it does not have Configuration, and ToDoContextFactory is used by migrations so the App is not running at all.

解决方案: 根据@JRB的回答,我使它像这样工作:

SOLUTION: Based on answer from @JRB I made it work like this:

public AppContext CreateDbContext(string[] args)
{
    string projectPath = AppDomain.CurrentDomain.BaseDirectory.Split(new String[] { @"bin\" }, StringSplitOptions.None)[0];
    IConfigurationRoot configuration = new ConfigurationBuilder()
        .SetBasePath(projectPath)
        .AddJsonFile("appsettings.json")
        .Build();
    string connectionString = configuration.GetConnectionString("DefaultConnection");

    var builder = new DbContextOptionsBuilder<AppContext>();
    builder.UseSqlServer(connectionString);

    return new AppContext(builder.Options);
}

推荐答案

步骤1:在OnConfiguring()中包括以下内容

STEP 1: Include the following in OnConfiguring()

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();
        optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
    }

第2步:创建appsettings.json:

STEP 2: Create appsettings.json:

  {
    "ConnectionStrings": {       
      "DefaultConnection": "Server=YOURSERVERNAME; Database=YOURDATABASENAME; Trusted_Connection=True; MultipleActiveResultSets=true"        
    } 
  }

步骤3:将appsettings.json硬拷贝到正确的目录

STEP 3: Hard copy appsettings.json to the correct directory

  Hard copy appsettings.json.config to the directory specified in the AppDomain.CurrentDomain.BaseDirectory directory. 
  Use your debugger to find out which directory that is.        

假设:您已经在项目中包含了Microsoft.Extensions.Configuration.Json包(从Nuget获取).

Assumption: you have already included package Microsoft.Extensions.Configuration.Json (get it from Nuget) in your project.

这篇关于从appsettings.json获取ConnectionString,而不是在.NET Core 2.0 App中进行硬编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆