Click here to Skip to main content
15,436,489 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my net core Web app I have an interface, a concrete class and a section in appsettings.json I would like to inject into the DI chain thus
Startup.cs
services.Configure<APIHost>(Configuration.GetSection("APIHosts"));
services.AddSingleton<IAPIHost,APIHost>();


I do this regularly with other sections of appsettings without a problem, the difference being, this is an array.

Here are the relevant files

IAPIHost.cs
namespace CommandsWebsite.Interfaces
{
    public interface IAPIHost
    {
        List<string> APIHosts { get; set; }
    }
}

APIHost.cs
namespace CommandsWebsite.Models
{
    public class APIHost : IAPIHost
    {
        public List<string> APIHosts {get;set;}
        
        public APIHost()
        {
        }
    }
}


appsettings.json
"APIHosts": ["NUC","M4V101","M4V102","M4V201","M4V202","M4V203"]

public TestController(IAPIHost APIHost)
{
	APIHost.APIHosts // always null
}


What I have tried:

Everything I show in code, If I inject IConfiguration the Controller and use the code below I get the array, but I would like it to happen using services.Configure
this.Configuration.GetSection("APIHosts").Get<List<string>>();


The APIHost.APIHosts List is always null.
Posted
Updated 27-Dec-21 0:34am

1 solution

I have it sussed - you need a class that exactly matches the appsetting section
appsettings section
"APIHost": {
    "APIHosts": [ "NUC", "M4V101", "M4V102", "M4V201", "M4V202", "M4V203" ]
  }


public class APIHost : IAPIHost
    {
        public APIHost()
        {
        }

        public List<string> APIHosts {get;set;}
    }


And these lines in Startup.cs to bind the array

services.Configure<APIHost>(options => this.Configuration.GetSection("APIHost").Bind(options));
services.AddSingleton<IAPIHost,APIHost>();


And inject this in the Controller constructor
MyController(IOptions<APIHost> options)


and it works
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900