use*_*668 6 c# asp.net npgsql asp.net-core asp.net-core-1.0
我是ASP.NET Core RC2的新手,我想知道如何获得一些配置设置并将其应用到我的方法中.对于我的实例appsettings.json
我有这个特定的设置
"ConnectionStrings": {
"DefaultConnection":
"Server=localhost;User Id=postgres;port=5432;Password=castro666;Database=dbname;"
}
Run Code Online (Sandbox Code Playgroud)
在我的Controller中,每次我想查询数据库时,我都必须使用此设置
using (var conn =
new NpgsqlConnection(
"Server=localhost;User Id=postgres;port=5432;Password=castro666;Database=dbname;"))
{
conn.Open();
}
Run Code Online (Sandbox Code Playgroud)
这里显而易见的是,如果我想在配置中添加更多内容,我必须更改该方法的每个实例.我的问题是如何才能进入DefaultConnection
,appsettings.json
这样我才能做到这一点
using (var conn =
new NpgsqlConnection(
ConfigurationManager["DefaultConnection"))
{
conn.Open();
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*ine 12
在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();
}
Run Code Online (Sandbox Code Playgroud)
我们现在JSON
已从构建器中读取配置并将其分配给我们的Configuration
实例.现在,我们需要将其配置为依赖注入 - 所以让我们首先创建一个简单的POCO来保存连接字符串.
public class ConnectionStrings
{
public string DefaultConnection { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我们正在实现"选项模式",我们将强类型类绑定到配置段.现在,ConfigureServices
执行此操作:
public void ConfigureServices(IServiceCollection services)
{
// Setup options with DI
services.AddOptions();
// Configure ConnectionStrings using config
services.Configure<ConnectionStrings>(Configuration);
}
Run Code Online (Sandbox Code Playgroud)
现在这一切都已到位,我们可以简单地要求类的构造函数接受,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...
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我一直建议必须阅读的官方文档.
小智 5
ConfigurationManager.AppSettings
引用 NuGet 包后可在 .NET Core 2.0 中使用System.Configuration.ConfigurationManager