在vNext中从appsetting.json读取启动后的连接字符串 [英] read connectionstring outside startup from appsetting.json in vNext
本文介绍了在vNext中从appsetting.json读取启动后的连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个项目课程(Nuget软件包).我需要在没有构造函数的静态类中读取与MongoDB的连接字符串.
I have a project class (Nuget Package). I need to read in a static class without constructor my connections string to 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);
}
我总是为空...如何在不使用DI的情况下获取Startup.cs之外的值?
I have always null... How can I obtain the value outside the Startup.cs without using DI?
有可能吗?
在我的旧代码中,我可以做类似的事情:
In my old code I could do something like that:
/// <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
Inside your startup, you should save the connection string to a static property on 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");
}
// ...
}
那么您应该可以从任何地方访问它:
Then you should be able to access it from wherever:
public static string GetDefaultConnectionString()
{
return Startup.ConnectionString;
}
这篇关于在vNext中从appsetting.json读取启动后的连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文