Injecting strongly typed data from a .NET Core appsettings.json file

Suppose you have the following section in your appsettings.json file in a .NET Core project:

"Domains": [
    {
      "Id": "324",
      "Name": "Domain1"
    },
    {
      "Id": "322",
      "Name": "Domain2"
    }
]

You can access these values by injecting IConfiguration but there is a way to map this data to a strongly typed list that can be injected anywhere you need it. Having it strongly typed makes it much easier to use.

To do this, you need to create an object that represents your config data structure:

    public class Domain
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Next, in your Startup.cs file, in the public void ConfigureServices(IServiceCollection services) function, you need to add this line which adds the strongly typed config to the services collection allowing you to inject where needed:

services.Configure<List<Domain>>(Configuration.GetSection("Domains"));

To inject the domains into a Controller or wherever you need it, you simply need to do the following:

    public class MyService: IMyService
    {
        private readonly List<Domain> _domains;

        public MyService(IOptions<List<Domain>> domains)
        {
            _domains= domains.Value;
        }
    }

You can then use the _domains in the same way that you would use any other list of objects.

To use IOptions you will need need to reference via Nuget Microsoft.Extensions.Configuration and Microsoft.Extensions.Options

Leave a Reply

Your email address will not be published. Required fields are marked *