3

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.

Community
  • 1
  • 1
SrdTLT
  • 123
  • 2
  • 13

2 Answers2

5

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.

Joe Audette
  • 35,330
  • 11
  • 106
  • 99
5

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.

Henk Mollema
  • 44,194
  • 12
  • 93
  • 104