Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hot to access appsettings.json from another project in same solution?

I have a solution with two projects:

  • ASP.NET Core 6 Web API Project
  • Class Library Project

I want to access the appsettings.josn file in the web api project from within the class library.

The api project already has a reference to the class library (Request/Response Models, Services, Handlers...etc).

Adding a reference for the api project to the class library would create a circular reference problem.

What's the best solution for this problem? Do I ditch the 2-project solution structure and place everything under 1 project?

like image 297
Taher Elhouderi Avatar asked Nov 18 '25 21:11

Taher Elhouderi


1 Answers

We do not recommend using the ConfigurationManager Class in the class library to get the value of appsettings.json.

Reason:

Keep your class library flexible,don't do this in your class library. And Dependency Injection becomes a very flexible and powerful tool.

Best Practise

How to use the IOptions pattern for configuration in ASP.NET Core RC2

Test Steps And Result

Program.cs

builder.Services.Configure<AppSettingsModel>(builder.Configuration.GetSection("ApplicationSettings"));

builder.Services.AddOptions();

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApplicationSettings": {
    "SmtpHost": "aa",
    "EmailRecipients": "bb"
  }
}

Model and test method in ClassLibrary.

enter image description here

Test Method in Controller

public string GetValue()
{
    GetValue g = new GetValue();
    string result = g.fortest(_settings.Value.SmtpHost,_settings.Value.EmailRecipients);
    return result;
}

enter image description here

Test Result

enter image description here

like image 199
Jason Pan Avatar answered Nov 22 '25 04:11

Jason Pan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!