How to use ConfigurationBinder in Configure method of startup.cs

asp.net mvc 6 beta5

I’ve tried to use config.json to activatedisactive 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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x