我有一个项目类(Nuget Package).我需要在没有构造函数的静态类中读取我的连接字符串到MongoDB.
静态类方法:
////// The default key MongoRepository will look for in the appsettings.json /// private const string DefaultConnectionstringName = "Data:MongoDB:MongoServerSettings"; ////// Retrieves the default connectionstring from appsettings.json /// ///Returns the default connectionstring from the App.config or Web.config file. public static string GetDefaultConnectionString() { var config = new Configuration(); return config.Get(DefaultConnectionstringName); }
我总是null ...如何在不使用DI的情况下获取Startup.cs之外的值?
有可能的?
在我的旧代码中,我可以做类似的事情:
////// Retrieves the default connectionstring from the App.config or Web.config file. /// ///Returns the default connectionstring from the App.config or Web.config file. public static string GetDefaultConnectionString() { return ConfigurationManager.ConnectionStrings[DefaultConnectionstringName].ConnectionString; }
谢谢!!
1. appsetting.json中的.ConnectionString
在Startup.cs类中创建Singleton Configuration of Configuration
使用依赖注入从配置实例读取值[构造函数注入]
最后输出
在启动内部,您应该将连接字符串保存到静态属性上 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("Data:MongoDB:MongoServerSettings"); } // ... }
然后你应该能够从任何地方访问它:
public static string GetDefaultConnectionString() { return Startup.ConnectionString; }
这样的事情应该起作用:
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath).AddJsonFile("config.json"); Configuration = builder.Build(); var connStr = Configuration.Get("connString"); }
文件:http://docs.asp.net/en/latest/fundamentals/configuration.html