N
N
Nik Faraday2022-02-07 23:09:03
ASP.NET
Nik Faraday, 2022-02-07 23:09:03

How to make a static config class in Asp.Net Core 6?

Hello!

There was a need to create a static configuration class, but in the Program.cs configuration file, the IServicesCollection object refuses to register it. Something similar on one forum, I attached a link to the question below

https://question-it.com/questions/116799/konfigura...

But I use .Net 6 and I don’t understand a little how to implement it correctly here without coding the floor project.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2022-02-07
@NikFaraday

You make a non-static configuration, and then, during initialization, you put an instance of the config in a public static property.
In .NET 6, this can be done something like this:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
GlobalConfig.Instance = app.Configuration;

app.MapGet("/", () => $"I can use configuration w/o DI! AllowedHosts={GlobalConfig.Instance.GetValue<string>("AllowedHosts")}");

app.Run();

public static class GlobalConfig
{
    public static IConfiguration Instance { get; set; }
}

But better not)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question