【问题标题】:Asp.Net core how can I replace the Configuration ManagerAsp.Net core如何更换配置管理器
【发布时间】:2016-09-22 08:43:10
【问题描述】:

我是 ASP.NET Core RC2 的新手,我想知道如何获取一些配置设置并将其应用于我的方法。例如在我的appsettings.json我有这个特定的设置

"ConnectionStrings": {
    "DefaultConnection": 
        "Server=localhost;User Id=postgres;port=5432;Password=castro666;Database=dbname;"
  }

每次我想在我的控制器中查询数据库时,我都必须使用这个设置

 using (var conn = 
     new NpgsqlConnection(
         "Server=localhost;User Id=postgres;port=5432;Password=castro666;Database=dbname;"))
 {
     conn.Open();
 }

这里明显的缺陷是,如果我想在配置中添加更多内容,我必须更改该方法的每个实例。我的问题是如何在appsettings.json 中获得DefaultConnection,以便我可以做这样的事情

 using (var conn = 
     new NpgsqlConnection(
         ConfigurationManager["DefaultConnection"))
 {
     conn.Open();
 }

【问题讨论】:

标签: c# asp.net asp.net-core npgsql asp.net-core-1.0


【解决方案1】:

ConfigurationManager.AppSettings
在引用 NuGet 包后在 .NET Core 2.0 中可用
System.Configuration.ConfigurationManager

【讨论】:

  • 我很高兴他们添加了这个。感谢您的信息。
【解决方案2】:

ASP.NET Core 中,您可以使用许多选项来访问配置。如果您对访问DefaultConnection 感兴趣,您最好使用 DI 方法。为了确保您可以使用构造函数依赖注入,我们必须在我们的Startup.cs 中正确配置一些东西。

public IConfigurationRoot Configuration { get; }

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}

我们现在已经从构建器中读取了我们的配置JSON,并将其分配给了我们的Configuration 实例。现在,我们需要配置它以进行依赖注入 - 所以让我们首先创建一个简单的 POCO 来保存连接字符串。

public class ConnectionStrings
{
    public string DefaultConnection { get; set; }
}

我们正在实现"Options Pattern",我们将强类型类绑定到配置段。现在,在ConfigureServices 中执行以下操作:

public void ConfigureServices(IServiceCollection services)
{
    // Setup options with DI
    services.AddOptions();

    // Configure ConnectionStrings using config
    services.Configure<ConnectionStrings>(Configuration);
}

现在一切就绪,我们可以简单地要求类的构造函数采用IOptions&lt;ConnectionStrings&gt;,我们将获得一个包含配置值的类的物化实例。

public class MyController : Controller
{
    private readonly ConnectionStrings _connectionStrings;

    public MyController(IOptions<ConnectionString> options)
    {
        _connectionStrings = options.Value;
    }

    public IActionResult Get()
    {
        // Use the _connectionStrings instance now...
        using (var conn = new NpgsqlConnection(_connectionStrings.DefaultConnection))
        {
            conn.Open();
            // Omitted for brevity...
        }
    }
}

Here 是我一直建议的官方文档,必须阅读

【讨论】:

  • 非常感谢您的详细解释,我现在也将阅读文档。
  • 只需要这九个简单的步骤! :)
猜你喜欢
  • 2020-02-01
  • 2015-08-18
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 2013-10-14
相关资源
最近更新 更多