2

I started some basic project on .net Core 1.1, and I wish to map some properties from appsettings.json to object, but I probably can't understand correct name convention or something pretty basic

Regarding MSDN Using Options and configuration objects section, it is very easy to use it. I added next lines to appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },

  "XXXOptions": {
    "X1": {
      "AppId": "11",
      "AppCode": "22"
    },
    "X2": {
      "AppId": "",
      "AppCode": ""
    }
  }
}

I added custom class

 public class XXXOptions
    {
        public XXXOptions()
        {
        }
        public X1 X1{ get; set; }
        public X2 X2{ get; set; }
    }

    public class X1
    {
        public int AppId { get; set; }
        public int AppCode { get; set; }
    }

    public class X2
    {
        public int AppId { get; set; }
        public int AppCode { get; set; }
    }

I added next code to Startup.cs

  public void ConfigureServices(IServiceCollection services)
        {
            // Adds services required for using options.
            services.AddOptions();

            // Register the IConfiguration instance which MyOptions binds against.
            services.Configure<XXXOptions>(Configuration);

            // Add framework services.
            services.AddMvc();
        }

 public class XXXController : Controller
    {
        private readonly XXXOptions _options;
        public XXXController(IOptions<XXXOptions> optionsAccessor)
        {
            _options = optionsAccessor.Value;
        }

        public IActionResult Index()
        {
            var option1 = _options.X1;
            return Content($"option1 = {option1.AppCode}, option2 = {option1.AppId}");
            return View();
        }
    }

optionsAccessor.Value - Value containes null values at XXXController constructor.

but it seems like framework show mappet values at JsonConfigurationProvider inside of Configuration property

any ideas?

1 Answer 1

7

In ConfigureServices method change:

services.Configure<XXXOptions>(Configuration);

to

services.Configure<XXXOptions>(Configuration.GetSection("XXXOptions"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.