【问题标题】:Json Connection strings - IConfiguration .net coreJson 连接字符串 - IConfiguration .net 核心
【发布时间】:2019-09-22 19:49:12
【问题描述】:

我正在尝试访问存储在应用程序中的连接。我的解决方案有两个项目,一个是数据库项目 (DAL),另一个是 WEB API。

在 web api 上,我有一个 App.settings,其中包含两个环境的连接字符串。

我正在尝试将 DBContext 配置为从那里获取连接字符串。

我做错了什么?

DAL 项目:

数据库上下文:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using DAL.Models.ProcedureModels;
using DAL;
using Microsoft.Extensions.Configuration;

..........

       public DBContext()
        {
        }

        public DBContext(DbContextOptions<DBContext> options)
            : base(options)
        {
        }

.........
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                IConfiguration configuration;
                optionsBuilder.UseSqlServer(configuration.GetConnectionString("local"));
            }
        }

Web API 项目中的 JSON 文件:

{
  "ConectionStrings": {
    "local": "............",
    "staging": "..........",
    "staging_ashure": "",
    "production": ""
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

【问题讨论】:

    标签: c# sql-server asp.net-core configuration environment-variables


    【解决方案1】:
    IConfiguration configuration;
    optionsBuilder.UseSqlServer(configuration.GetConnectionString("local"));
    

    这声明了一个未初始化的变量configuration,因此它不包含任何值,然后立即尝试使用它。这行不通。您必须先初始化 configuration 变量。

    但这并不能真正帮助您,因为您需要从此处的 Web 应用程序中实际获取配置。

    我建议您不要使用OnConfiguring,而是使用带有DbContextOptions 的构造函数,然后依靠应用程序从您的库中正确注册数据库上下文。

    所以在您的网络应用程序的StartupConfigureServices 内,添加以下内容:

    services.AddDbContext<DBContext>(options =>
    {
        options.UseSqlServer(configuration.GetConnectionString("local"));
    });
    

    在那里,DBContext 将是您的 DAL 项目中的类型。

    【讨论】:

      【解决方案2】:

      如果您坚持访问DBContext 中的连接字符串,您可以尝试从服务集合中解析IConfiguration

      public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
      {
          private readonly IConfiguration _configuration;
          public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options,
              IConfiguration configuration)
              : base(options)
          {
              _configuration = configuration;
          }
          protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
          {
              if (!optionsBuilder.IsConfigured)
              {
                  var connectionString = _configuration.GetConnectionString("local");
                  optionsBuilder.UseSqlServer(_configuration.GetConnectionString("local"));
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-05-02
        • 2019-03-10
        • 2020-01-07
        • 2020-07-21
        • 2021-03-09
        • 1970-01-01
        • 2018-02-21
        • 2019-05-15
        • 2023-04-08
        相关资源
        最近更新 更多