c# - Asp.Net core 如何替换配置管理器

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

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

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

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

 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();
 }

最佳答案

ASP.NET Core 中,您可以使用许多选项来访问配置。好像如果你感兴趣它访问 DefaultConnection你最好使用 DI 方法。为了确保您可以使用构造函数依赖注入(inject),我们必须在 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来自 builder 并将其分配给我们的 Configuration实例。现在,我们需要为依赖项注入(inject)配置它 - 所以让我们从创建一个简单的 POCO 开始来保存连接字符串。

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

我们正在实现 "Options Pattern"我们将强类型类绑定(bind)到配置段的地方。现在,在 ConfigureServices这样做:

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

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

现在一切就绪,我们可以简单地要求类的构造函数接受 IOptions<ConnectionStrings>。我们将获得包含配置值的类的物化实例。

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是我一直建议作为必读的官方文档。

关于c# - Asp.Net core 如何替换配置管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37425369/

相关文章:

c# - 创建 MVC 删除按钮扩展 - 如何扩展 MVC 的 Html 助手?

c# - CMS 6.5 和 7.0 之间的 Sitecore FieldRenderer 输出差异

javascript - NumericTextBox 使用 Html.TextBoxFor 丢失值,而不是 HTML

C# azure : How to set Azure timeout and retry policy when running locally?

c# - 从 JVM 中执行 C#

c# - ASP.NET MVC 复杂模型更新

c# - 如何使用 jquery 将 json 数据发送到 asmx(从 aspx)?

c# - asp.net BLL 类中的各种缓存选项

azure - 如何使用azure功能启动停止azure应用程序服务计划

c# - 在 MVC 程序中调用 Web API