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.