如何使用 .NET Core 配置框架将连接字符串放置到 json 配置文件?

How to place a connection string to a json configuration file using .NET Core Configuration framework?

我的解决方案有 3 个项目:

我想创建迁移到实体项目中的函数。 在实体项目中,我有一个 class TemporaryDbContextFactory

public class TemporaryDbContextFactory : IDbContextFactory<MyContext>
    {


        public ApplicationContext Create(DbContextFactoryOptions options)
        {
            var builder = new DbContextOptionsBuilder<MyContext>();
            builder.UseSqlServer("Server=(local)\mssqllocaldb;Database=mydatabase;Trusted_Connection=True;MultipleActiveResultSets=true;User ID=sa; Password=123456",
                optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(MyContext).GetTypeInfo().Assembly.GetName().Name));
            return new MyContext(builder.Options);
        }
    }

但在这里我不想使用硬编码连接字符串我尝试为动态连接字符串创建应用程序设置:

public class MyContextFactory : IDbContextFactory<ApplicationContext>
    {
        public MyContext Create()
        {
            var environmentName =
                        Environment.GetEnvironmentVariable(
                            "Hosting:Environment");

            var basePath = AppContext.BaseDirectory;

            return Create(basePath, environmentName);
        }

        public MyContext Create(DbContextFactoryOptions options)
        {
            return Create(
                options.ContentRootPath,
                options.EnvironmentName);
        }

        private MyContext Create(string basePath, string environmentName)
        {
            var configuration = new Configuration();
            configuration.AddJsonFile(“config.json”);
            var emailAddress = configuration.Get("emailAddress");

            var builder = new ConfigurationBuilder()
                .SetBasePath(basePath)
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{environmentName}.json", true)
                .AddEnvironmentVariables();


            var config = builder.Build();

            var connstr = config.GetConnectionString("(default)");

            if (String.IsNullOrWhiteSpace(connstr) == true)
            {
                throw new InvalidOperationException(
                    "Could not find a connection string named '(default)'.");
            }
            else
            {
                return Create(connstr);
            }
        }

        private MyContext Create(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentException(
                    $"{nameof(connectionString)} is null or empty.",
                    nameof(connectionString));

            var optionsBuilder =
                new DbContextOptionsBuilder<MyContext>();

            optionsBuilder.UseSqlServer(connectionString);

            return new MyContext(optionsBuilder.Options);
        }
    }

我一直在创建这个

的实例
var configuration = new Configuration();

实体项目没有对 Microsoft.Extensions.Configuration 的任何引用 我不知道如何添加它,因为我找不到它。请帮我添加这个参考或建议我不同的方式

这是一个新的配置框架,习惯后你会喜欢的:

var configuration = new ConfigurationBuilder()
   .AddJsonFile("config.json")
   .Build();
var emailAddress = configuration.GetValue<string>("emailAddress");

您需要安装以下 nuget 包: Microsoft.Extensions.Configuration.Json Microsoft.Extensions.Configuration.ConfigurationBinder

如果您没有看到它,请确保您使用的是正确的提要。查看包管理器的 Package Source 组合框,它应该是 nuget.org.

另外,确保 config.json 配置文件被复制到输出:

{
   "emailAddress" : "some@example.com"
}

具体关于连接字符串,请查看此示例:https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings#aspnet-core