I am new to ASP.NET Core RC2 and I was wondering how can I get some configuration settings and apply it to my method. For Instance in my appsettings.json
I have this specific setting
我是ASP.NET Core RC2的新手,我想知道如何获得一些配置设置并将其应用于我的方法。对于我的appsettings.json中的实例,我有这个特定的设置
"ConnectionStrings": {
"DefaultConnection":
"Server=localhost;User Id=postgres;port=5432;Password=castro666;Database=dbname;"
}
In my Controller every time I want to query the database I have to use this setup
在我的控制器中,每次我想查询数据库时,我都必须使用此设置
using (var conn =
new NpgsqlConnection(
"Server=localhost;User Id=postgres;port=5432;Password=castro666;Database=dbname;"))
{
conn.Open();
}
The obvious pitfull here is that if I want to add more to the configuration I have to change every single instance of that method. My question is how can I get the DefaultConnection
in the appsettings.json
so that I can do something like this
这里显而易见的是,如果我想在配置中添加更多内容,我必须更改该方法的每个实例。我的问题是如何在appsettings.json中获取DefaultConnection,以便我可以做这样的事情
using (var conn =
new NpgsqlConnection(
ConfigurationManager["DefaultConnection"))
{
conn.Open();
}
2 个解决方案
#1
11
In ASP.NET Core there are a lot of options you can use to access the configuration. It seems like if you're interesting it accessing the DefaultConnection
you'd be better off using the DI approach. In order to ensure that you can use constructor dependency injection we have to correctly configure a few things in our Startup.cs
.
在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();
}
We have now read our configuration JSON
from the builder and assigned it to our Configuration
instance. Now, we'll need to configure it for dependency injection - so let's start by creating a simple POCO to hold the connection string.
我们现在已从构建器中读取配置JSON并将其分配给我们的Configuration实例。现在,我们需要将其配置为依赖注入 - 所以让我们首先创建一个简单的POCO来保存连接字符串。
public class ConnectionStrings
{
public string DefaultConnection { get; set; }
}
We are implementing the "Options Pattern" where we bind strongly-typed classes to configuration segments. Now, in ConfigureServices
do this:
我们正在实现“选项模式”,我们将强类型类绑定到配置段。现在,在ConfigureServices中执行以下操作:
public void ConfigureServices(IServiceCollection services)
{
// Setup options with DI
services.AddOptions();
// Configure ConnectionStrings using config
services.Configure<ConnectionStrings>(Configuration);
}
Now that this is all in place, we can simply require the constructor of the class to take on the IOptions<ConnectionStrings>
and we'll be given a materialized instance of the class containing the configuration values.
现在这一切都已到位,我们可以简单地要求类的构造函数接受IOptions
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 is the official documentation which I always suggest as a must read.
这是我一直建议必须阅读的官方文档。
#2
1
ConfigurationManager.AppSettings
is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager
在引用NuGet包System.Configuration.ConfigurationManager之后,ConfigurationManager.AppSettings在.NET Core 2.0中可用。
#1
11
In ASP.NET Core there are a lot of options you can use to access the configuration. It seems like if you're interesting it accessing the DefaultConnection
you'd be better off using the DI approach. In order to ensure that you can use constructor dependency injection we have to correctly configure a few things in our Startup.cs
.
在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();
}
We have now read our configuration JSON
from the builder and assigned it to our Configuration
instance. Now, we'll need to configure it for dependency injection - so let's start by creating a simple POCO to hold the connection string.
我们现在已从构建器中读取配置JSON并将其分配给我们的Configuration实例。现在,我们需要将其配置为依赖注入 - 所以让我们首先创建一个简单的POCO来保存连接字符串。
public class ConnectionStrings
{
public string DefaultConnection { get; set; }
}
We are implementing the "Options Pattern" where we bind strongly-typed classes to configuration segments. Now, in ConfigureServices
do this:
我们正在实现“选项模式”,我们将强类型类绑定到配置段。现在,在ConfigureServices中执行以下操作:
public void ConfigureServices(IServiceCollection services)
{
// Setup options with DI
services.AddOptions();
// Configure ConnectionStrings using config
services.Configure<ConnectionStrings>(Configuration);
}
Now that this is all in place, we can simply require the constructor of the class to take on the IOptions<ConnectionStrings>
and we'll be given a materialized instance of the class containing the configuration values.
现在这一切都已到位,我们可以简单地要求类的构造函数接受IOptions
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 is the official documentation which I always suggest as a must read.
这是我一直建议必须阅读的官方文档。
#2
1
ConfigurationManager.AppSettings
is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager
在引用NuGet包System.Configuration.ConfigurationManager之后,ConfigurationManager.AppSettings在.NET Core 2.0中可用。