Breaking News:

banner image

Home Design

{recent}{block-1}{4}

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

 

access-configuration-settings-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:

access-configuration-settings-asp-net-core-6-0-static-class

The Exception

When I tried to get appsettings value within my controller:

access-configuration-settings-asp-net-core-6-0-app-setting-call

I got the error below:

access-configuration-settings-asp-net-core-6-0-error

The Solution

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

access-configuration-settings-asp-net-core-6-0-getrequired-services

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.

access-configuration-settings-asp-net-core-6-0-worked

I hope this helps someone.

How to Access Configuration Settings (IConfiguration) in Static Class ASP.Net Core 6.0 How to Access Configuration Settings (IConfiguration) in Static Class ASP.Net Core 6.0 Reviewed by Adesina Mark on July 30, 2022 Rating: 5

No comments:

Featured News

{recent}{block-8}{4}
Powered by Blogger.