1

I have 2 applications

  1. App
  2. ClassLibrary

App references ClassLibrary and both have their own appsettings.json file. My class library app has no startup.cs or program.cs so I have a static class that is supposed to read from the local appsettings.json file like this:

static class ConfigurationManager
{
    public static IConfiguration AppSetting { get; }
    static ConfigurationManager()
    {
        AppSetting = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();
    }
}

This is the appsettings.json in the class library

{
  "AccountsAddress": "http://localhost:55260/api/Accounts/"
}

The problem starts when my app runs, it calls a method located in class library. However, the appsettings that is called is not the one in class library. Its the one in the app itself. Is there a way to specify that I want to reference the appsettings in the class library instead of the App.

JianYA
  • 2,750
  • 8
  • 60
  • 136
  • 1
    A class library is a DLL, it's not an executable, it doesn't have a startup location to have an appsettings.json file. – Camilo Terevinto Oct 15 '18 at 23:38
  • The problem here is you are calling setbasepath on the current working directory with `Directory.GetCurrentDirectory()` so when you launch the app it reads the one in the app directory. See if this helps: https://stackoverflow.com/questions/15653921/get-current-folder-path – Avin Kavish Oct 15 '18 at 23:39

1 Answers1

4

Is there a way to specify that I want to reference the appsettings in the class library instead of the App.

Rename class library's appsettings.json file to something unique to that library.

something like {classlibname}.appsettings.json

After renaming it, make sure to set it to be copied to output directory.

Also make sure after renaming it that the code is calling the new name

//...
.AddJsonFile("classlibname.appsettings.json", optional: true, reloadOnChange: true)
//...
Nkosi
  • 235,767
  • 35
  • 427
  • 472