gpt4 book ai didi

c# - 在vNext中从appsetting.json读取启动后的连接字符串

转载 作者:行者123 更新时间:2023-12-03 13:38:56 25 4
gpt4 key购买 nike

我有一个项目类(class)(Nuget软件包)。我需要在没有构造函数的静态类中读取与MongoDB的连接字符串。

静态类方法:

        /// <summary>
/// The default key MongoRepository will look for in the appsettings.json
/// </summary>
private const string DefaultConnectionstringName = "Data:MongoDB:MongoServerSettings";

/// <summary>
/// Retrieves the default connectionstring from appsettings.json
/// </summary>
/// <returns>Returns the default connectionstring from the App.config or Web.config file.</returns>
public static string GetDefaultConnectionString()
{
var config = new Configuration();
return config.Get<string>(DefaultConnectionstringName);
}

我一直为null ...如何在不使用DI的情况下获取Startup.cs之外的值?

有可能的?

在我的旧代码中,我可以执行以下操作:
/// <summary>
/// Retrieves the default connectionstring from the App.config or Web.config file.
/// </summary>
/// <returns>Returns the default connectionstring from the App.config or Web.config file.</returns>
public static string GetDefaultConnectionString()
{
return ConfigurationManager.ConnectionStrings[DefaultConnectionstringName].ConnectionString;
}

谢谢!!

最佳答案

在启动过程中,应将连接字符串保存到Startup的静态属性中

public class Startup
{
public static string ConnectionString { get; private set; }

public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddUserSecrets();

if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}

builder.AddEnvironmentVariables();
Configuration = builder.Build();
ConnectionString = Configuration.Get<string>("Data:MongoDB:MongoServerSettings");
}
// ...
}

然后,您应该可以从任何地方访问它:
public static string GetDefaultConnectionString()
{
return Startup.ConnectionString;
}

关于c# - 在vNext中从appsetting.json读取启动后的连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34269106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com