floormind
floormind

Reputation: 2028

is there a way of making use of .json configurations in .net core class library instead of a .config file

I have a class library i want end up packaging into a nuget package, i have some configurations i wish to use which are in a json file (apsettings.json).

I have added this file to my class library project, and at the moment i just want to read the values in the configurations in a constructor without using a .config file, i will like to use a .json similar to how i'll do it in a web project.

I am trying something like this, but i get an error stating that the settings.json file does not exist in \bin\Debug\netcoreapp2.0. It is not in that folder, it is in the root of my project.

    public TokenGenerator()
    {
        var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json");
        _configuration = builder.Build();

        _tokenServiceSettings = new TokenServiceSettings()
        {
            Audience = _configuration.GetSection("JwtBearer:Audience").Value
        };
    }

At the moment, i have just hard coded the directory as a string inside the SetBasePath method

Upvotes: 0

Views: 414

Answers (2)

Kahbazi
Kahbazi

Reputation: 15015

If you are writing a library that other teams might use in other projects, you should not bind it to another package (Microsoft.Extensions.Configuration) just for configuration.

You should have your own Option class which is a simple class with bunch of properties

public class TokenServiceOptions
{
    public TokenServiceOptions()
    {
        Audience = "Audience_Default_Value!";
    }

    public string Audience { set; get; }
    public string OtherOption1 { set; get; }
    public string OtherOption2 { set; get; }
    ///
}

and let your library users pass an instance of TokenServiceOptions to your method.

It should not be important to a library how options are gathered.

Upvotes: 3

Emond
Emond

Reputation: 50712

Because this is in a library, this class cannot know where and what json file to read.

  • Pass the full path to the file to the library or,
  • Pass a structure as an argument to the library so the calling assembly can pass in the data and store it anywhere and any way it likes or
  • Get the location of the CallingAssembly (Assembly.GetCallingAssembly().Location) and construct a relative path to that.

Upvotes: 0

Related Questions