我正在尝试使用here描述的选项模式,但我希望能够获得比键/值对更复杂的东西。
理想情况下,我希望能够使用Paste JSON as Classes
复制我的appsettings.json,然后将根类交给services.Configure<T>(Configuration)
并完成。
这就是我所做的:
appsettings.json:
{
"Data": {
"ConnectionA": {
"ConnectionString": "string1"
},
"ConnectionB": {
"ConnectionString": "string2"
}
}
}
相应的课程
public class Data
{
public Connectiona ConnectionA { get; set; }
public Connectionb ConnectionB { get; set; }
}
public class Connectiona
{
public string ConnectionString { get; set; }
}
public class Connectionb
{
public string ConnectionString { get; set; }
}
startup.cs
services.Configure<Data>(Configuration);
这会返回ConnectionA
和ConnectionB
的空对象。
有什么建议吗?
每次请求完整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)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<Data>(Configuration);
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=User}/{action=Index}/{id?}");
});
}
修改:
这有效:
services.Configure<Data>(options => {
options.Connectiona = new Connectiona();
options.Connectiona = new Connectionb();
options.Connectiona.ConnectionString = Configuration["Data:Connectiona:ConnectionString"];
options.Connectionb.ConnectionString = Configuration["Data:Connectionb:ConnectionString"];
});
所以看起来我不能使用services.Configure<Data>(Configuration)
扩展名。
答案 0 :(得分:7)
尝试使用services.Configure<Data>(Configuration.GetSection("Data"));
代替services.Configure<Data>(Configuration);
答案 1 :(得分:0)
尝试这样:
{
"Data": {
"DataWarehouseConnection": {
"ConnectionString": "yourconnectionstringhere"
},
"DefaultConnection ": {
"ConnectionString": "yourconnectionstringhere"
}
}