从vNext中的appsetting.json读取启动外的连接字符串

时间:2015-12-14 14:11:54

标签: c# asp.net-core

我有一个项目类(Nuget Package)。我需要在没有构造函数的静态类中读取我的连接字符串到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;
    }

谢谢!

5 个答案:

答案 0 :(得分:38)

1. appsetting.json中的连接字符串

enter image description here

  1. 在Startup.cs类中创建单例配置实例
  2. enter image description here

    1. 使用依赖注入从[配置实例中读取值] [构造函数注入]
    2. enter image description here

      1. 最后输出
      2. enter image description here

答案 1 :(得分:21)

在启动内部,您应该将连接字符串保存到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;
}

答案 2 :(得分:4)

这样的事情应该有效:

   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

答案 3 :(得分:0)

  

如何在不使用DI的情况下获取Startup.cs之外的值?有可能吗?

是的,您可以在整个应用程序中使用不带DI的配置。但建议仅在启动时使用配置API,然后使用Using Options

  

创建与应用程序中某些功能相对应的设备良好的设置对象,从而遵循接口隔离原则(ISP)(类仅依赖于他们使用的配置设置)

使用配置API的示例

appsettings.json:

{
  "Name": "Stas",
  "Surname": "Boyarincev"
}

使用配置:

var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

var Configuration = builder.Build();

var name = Configuration.GetSection("name");
var surname = Configuration.GetSection("surname");

tutorial on docs.asp.net - 但有点过时了。

答案 4 :(得分:0)

以上所有答案均不适用于我。我正在构建.net核心2.1 API。

我用过

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


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
           if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            ConnectionString = Configuration.GetConnectionString("xxxxxx");
            app.UseMvc();
}

然后,每当我需要时,我都叫string ConnString = Startup.ConnectionString;