aspnet / Options

[Archived] A framework for accessing and configuring POCO settings. Project moved to https://github.com/aspnet/Extensions
Apache License 2.0
149 stars 67 forks source link

@inject does not work - all fields are always null. #91

Closed xatabhk closed 8 years ago

xatabhk commented 8 years ago

appsettings.cs:

   public class AppSettings
    {
        public string SiteTitle { get; set; }
    }

appsettings.json:

{
    "AppSettings": {
    "SiteTitle": "ZaxiTech"
  }

Startup.cs:

public static IConfiguration Configuration { get; set; }

services.AddOptions();  // Setup options with DI
services.Configure<AppSettings>(Configuration);

xview.cshtml:

@using Microsoft.Extensions.OptionsModel
@inject IOptions<AppSettings> MyAppSettings

And all fields like SiteTitle in MyAppSettings are always null.

PMExtra commented 8 years ago

I have the same problem, have you solved it?

davidfowl commented 8 years ago

Try

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
PMExtra commented 8 years ago

I got it, @davidfowl is right. I had read the docs and known "setup the IOptions service", but I misspelled the configuration section name >_<...

docs link: http://docs.asp.net/en/latest/fundamentals/configuration.html#using-options-and-configuration-objects

xatabhk commented 8 years ago

@davidfowl No. services.Configure(Configuration.GetSection("AppSettings")) works no more on latest RC2.

But I have found a workaround for this issue as follows: services.Configure((xx)=> { xx.SiteTitle=Configuration.GetSection("AppSettings")["SiteTitle"]; });

Still, settings are not loaded automatically.

davidfowl commented 8 years ago

@xatabhk It does work, the syntax (and namespace) probably changed

xatabhk commented 8 years ago

@davidfowl Buit it does not work as expected. User has to do property/field mapping manually like this: xx.SiteTitle=Configuration.GetSection("AppSettings")["SiteTitle"];

davidfowl commented 8 years ago

Nah, can you provide the fully non working sample? Pushing to a github repo with instructions would be best.

divega commented 8 years ago

@xatabhk the Configure<T>() extension methods that take an IConfiguration where moved to a new package (Microsoft.Extensions.Options.ConfigurationExtensions) to decouple dependencies. See #97 for more information.