asp.net mvc 6 beta5
I've tried to use config.json to activate\disactive logging
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
Configuration = configurationBuilder.Build();
DBContext.ConnectionString = Configuration.Get("Data:DefaultConnection:ConnectionString");
}
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings"));
}
// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory)
{
// that line cause NullReferenceException
AppSettings settings = ConfigurationBinder.Bind<AppSettings>(Configuration);
if (settings.Log.IsActive)
{
................
}
Example from ASP.NET 5 (vNext) - Getting a Configuration Setting and http://perezgb.com/2015/07/04/aspnet-5-typed-settings-with-the-configurationbinder/
Is there another way to get an instance of the AppSettings in the "configure" method? I need typed object.
Every service configured in ConfigureServices
can be injected in the Configure
method by the runtime:
public void Configure(IApplicationBuilder app, IOptions<AppSettings> options)
{
// access options.Options here
}
This is a bit cleaner solution than accessing the ServiceProvider
directly.
you can get it like this using service locator:
IOptions<AppSettings> settings = app.ApplicationServices.GetService<IOptions<AppSettings>>();
if (settings.Options.whatever)
{
...
}
I noticed that if you create a new project with the final release of VS 2015 the project template doesn't include AppSettings as the previous project template did, not sure why.
来源:https://stackoverflow.com/questions/31541944/how-to-use-configurationbinder-in-configure-method-of-startup-cs