如何从另一个项目访问位于一个项目中的配置文件

How to access a configuration file located in one project from another project

这是我当前项目中的数据库上下文设计工厂 class。要连接到我的数据库,它需要存储在配置文件 (_config.json) 中的连接字符串。

public class HiromiContextDesignFactory : IDesignTimeDbContextFactory<HiromiContext>
{
    public HiromiContext CreateDbContext(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath() // What is the path
            .AddJsonFile("_config.json")
            .Build();

        var builder = new DbContextOptionsBuilder<HiromiContext>()
            .UseNpgsql(configuration["Connections:Postgre"]);

        return new HiromiContext(builder.Options);
    }
}

但是,我的配置文件位于另一个项目的根目录中。因此,我不确定应该在 SetBasePath() 方法中使用什么路径来访问该文件。我应该如何解决这个问题?

将您的 "another" 项目添加为 "current" 项目的项目参考,确保将“_config.json”复制到 "another" 项目的输出目录build/project 设置,然后应将所有工件复制到当前项目的输出目录...

看起来这个问题很简单。 @aDisplayName 提供的答案非常好,如果您遇到同样的问题,这是一个可以接受的解决方案。但是,Microsoft 实际上建议使用 user secrets 来存储开发中的敏感数据。

因为数据库上下文设计工厂 class 只需要迁移(它与应用程序或数据库连接上下文的 运行ning 无关,那是为了您的常规上下文 class 继承自 DbContext) 我可以安全地将我的连接字符串存储为用户机密。

我已经链接了上面的文档来执行此操作,但这里是我所做操作的快速摘要。

导航到包含您的设计工厂class和运行命令的项目

dotnet user-secrets init
dotnet user-secrets set "Connections:Postgres" "CONNECTION_STRING"

然后,在您的配置生成器上调用 AddUserSecrets<T>() 方法,而不是设置基本路径。配置生成器应该看起来像这样。

var configuration = new ConfigurationBuilder()
            .AddUserSecrets<HiromiContext>() // This should be the name of the class that inherits from DbContext.
          //.AddUserSecrets(Assembly.GetEntryAssembly()) You can also do this if your database context and database design factory classes are in the same project, which should be the case 99% of the time
            .Build();