1

I'm working on a .net core 7 application. I have to implement a minimal api using a service class. In this service class, i've to access to appsettings. In the program.cs file, i have the following lines :

var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.Local.json", true);
builder.Configuration["groupParameterOne:ParameterA"];

I need to access to appsettings from a service class but i don't know how to inject the builder in my service class.

I can implement a static class to set and access my settings but i don't think it's the right way to do that.

Thanks in advance for your help.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Zen Christophe
  • 131
  • 2
  • 12
  • Does this answer your question? [Setting up authentication endpoints class in minimal API](https://stackoverflow.com/questions/74424984/setting-up-authentication-endpoints-class-in-minimal-api) – Guru Stron Nov 14 '22 at 14:54

1 Answers1

1

I'm using .net Maui and .net 7 and this is how I access appsettings in a Singleton.

In Program add to the builder.Configuration.AddJsonFile("appsettings.json", false); To the builder services add a singleton builder.Services.AddSingleton<AppSettingsReader>();

In the singleton service I want to be able to access the config settings in I create a private IConfiguration field called _configuration and then create a constructor and pass in IConfiguration setting the private field equal to config, so my constructor looks like this.

public TheSingletonService(IConfiguration config) { _configuration = config; }

Now I have access to config values stored in appsettings. You need to make sure that when adding the JSONFile you make sure to specify the file is required by passing in a value of false to the optional param.

technified
  • 353
  • 1
  • 2
  • 15