How to Access Configuration Settings (IConfiguration) in Static Class ASP.Net Core 6.0



Recently, I had a scenario that required resolving dependency injection in a static class within ASP.Net Core 6.0 application.

The Problem

We need to inject IConfiguration class within a static class in ASP.Net Core 6.0, This will require us to have a static constructor which is not supported for the .NET core to work for Constructor Injection.

The Static Class

I created a class below with IConfiguration Interface injected and then tried to access this within my controller:


The Exception

When I tried to get appsettings value within my controller:


I got the error below:


The Solution

The solution is to inject IConfiguration at run time using ServiceProviderServiceExtensions.GetRequiredService Method


In program.cs class in the root of the app, we need to add the line of code below. After this everything works just fine.


I hope this helps someone.

No comments:

Powered by Blogger.