Friday, May 8, 2020

Read appsettings.json in .net Core application with Dependency Injection (DI)

If you are truggling on how to read a constant setting or any setting value into a custom class / or any POCO class from the appsettings, and passing them back to the application that use .netCore and support DependencyInjection, then you are looking at the right post.

I have been struggling on this and here is what I found out.

In your webApp project, go to the Startup.cs, go to the method ConfigureServices, and add the following code:
it can be:
            var identitySettingsSection = Configuration.GetSection("AppIdentitySettingsConfig");
            services.Configure<AppIdentitySettingsConfig>(identitySettingsSection);

or
            services.Configure<AppIdentitySettingsConfig>(options => Configuration.GetSection("AppIdentitySettingsConfig").Bind(options));

Both are working same / fine. It will be looking like this:

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AppIdentitySettingsConfig>(options => Configuration.GetSection("AppIdentitySettingsConfig").Bind(options));

Important note is make sure the parameter after GetSection is exactly the same as per your config file.

Next are how i set up for the other files.


Tthis is how I configure my appsetings.json.
{
  "AppIdentitySettingsConfig": {
    "Section1": {
      "DummyServiceUrl": "https://localhost:44339",
      "ApplicationServiceUrl": "https://localhost:44339"
    },
    "Section2": [
      {
        "Url": "https://localhost:44339"
      },
      {
        "Url": "https://localhost:44339"
      }
    ]
  },
}

Then, for the custom model class / POCO class
    public class AppIdentitySettingsConfig
    {
        public Section1Class Section1 { get; set; }
        public List<Section2Class> Section2 { get; set; }
    }

    public class Section1Class
    {

        public string DummyServiceUrl { get; set; }
        public string ApplicationServiceUrl { get; set; }
    }

    public class Section2Class
    {
        public string Url { get; set; }
    }

remember, the parameter must have same name as per the settings'.

Then, in the class that you want to retrieve the settings, first, inject the Ioptions that you just registered, and then you can free to use it anywhere. It can be in controller or business service or any layer in the code. eg:

 public class SampleServiceClass : ISampleServiceClass
   {
        IOptions<AppIdentitySettingsConfig> _settings;

        public SampleServiceClass(IOptions<AppIdentitySettingsConfig> settings)
        {
            _settings = settings;
        }

        public void  AnySampleMethod()
        {            
                string webAPIURL = _settings.Value.Section1.ApplicationServiceUrl;
                
        }
   }

Tada! Done. :D

No comments:

Post a Comment