我有一个ASP.NET核心应用程序。我尝试使用选项模式,但它似乎不起作用。
我有以下appsettings.json
:
{
"ConnectionStrings": {
"MyTablesConnectionString": "Default[...];EndpointSuffix=core.windows.net"
},
"Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }
}
以下ConnectionStrings
课程
public class ConnectionStrings {
public ConnectionStrings() {
MyTablesConnectionString = "default value";
}
public string MyTablesConnectionString { get; set; }
}
这是我的Startup.cs
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
// HERE IS THE GOOD VALUE !!!!!!!!
Debug.WriteLine($"Connection string is:{Configuration["ConnectionStrings:MyTablesConnectionString"]}");
}
public void ConfigureServices(IServiceCollection services)
{
// Adds services required for using options.
services.AddOptions();
// Register the IConfiguration instance which "ConnectionStrings" binds against.
services.Configure<ConnectionStrings>(Configuration);
// Add framework services.
services.AddMvc();
}
但是,在使用以下控制器的开发机器上使用它时
private readonly ConnectionStrings azureConnectionString;
public HelloWorldController(IOptions<ConnectionStrings> optionsAccessor)
{
// HERE IS THE "DEFAULT" VALUE ?!!!!!!!!
azureConnectionString = optionsAccessor.Value;
}
我看到&#34;默认值&#34;而不是使用json文件中的值(无效的一个)。我错过了什么吗?
答案 0 :(得分:5)
您需要绑定ConnectionStrings部分,如下所示:
services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
目前,您希望从您的班级中找到属性“ConnectionStrings”或“Logging”,因为您绑定了根。
答案 1 :(得分:0)
或者,配置所有options automatically
PM> Install-Package Register.Options.Asp.Net.Core
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureOptionsFromAssemblies(configuration, new List<Assembly>()
{
typeof(ConnectionStrings).Assembly
});
...
}
免责声明package
的作者