Access from class library to appsetting.json in Asp.net-core

C#asp.net Core.Net Coreasp.net Core-Mvc

C# Problem Overview


I am trying to access appsetting.json file from a class library. So far the solution that I found is to create a configuration class implementing interface IConfiguration from Microsoft.Extensions.Configuration and add the json file to class and read from the same.

var configuration = new Configuration();
configuration.AddJsonFile("appsetting.json");
var connectionString= configuration.Get("connectionString");

This seems to be bad option as we have to add the json file each time we have to access the appsetting configuration. Dont we have any alternative like ConfigurationManager in ASP.NET.

C# Solutions


Solution 1 - C#

I know an answer has already been accepted, but this questions is a top hit on Google and OPs question is about class libraries and not an ASP.NET Web App or a WebApi which is what the accepted answer uses.

IMO, class libraries should not use application settings and should be agnostic to such settings. If you need application settings in your class library, then you should provide those settings from your consumer. You can see an example of this On This SO Question

Solution 2 - C#

I'm assuming you want to access the appsettings.json file from the web application since class libraries don't have an appsettings.json by default.

I create a model class that has properties that match the settings in a section in appsettings.json.

Section in appsettings.json

"ApplicationSettings": {
    "SmtpHost": "mydomain.smtp.com",
    "EmailRecipients": "[email protected];[email protected]"
}   

Matching model class

namespace MyApp.Models
{
    public class AppSettingsModel
    {
        public string SmtpHost { get; set; }
        public string EmailRecipients { get; set; }
    }
}

Then populate that model class and add it to the IOptions collection in the DI container (this is done in the Configure() method of the Startup class).

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

// Other configuration stuff

services.AddOptions();

Then you can access that class from any method that the framework calls by adding it as a parameter in the constructor. The framework handles finding and providing the class to the constructor.

public class MyController: Controller
{
    private IOptions<AppSettingsModel> settings;

    public MyController(IOptions<AppSettingsModel> settings)
    {
        this.settings = settings;
    }
}

Then when a method in a class library needs the settings, I either pass the settings individually or pass the entire object.

Solution 3 - C#

Besides the questions has an accepted answer, I believe that there is no one that applies to just a class library without having Startup projects or having dependencies with Asp.NetCore stack or IServiceCollection.

This is how I achieved to read the config from a class library:

using Microsoft.Extensions.Configuration;
using System.IO;

public class ConfigSample
{
    public ConfigSample
    {
            IConfigurationBuilder builder = new ConfigurationBuilder();
            builder.AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"));

            var root = builder.Build();
            var sampleConnectionString = root.GetConnectionString("your-connection-string");
    }
}

The following nuget packages are required:

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.FileProviders.Abstractions
  • Newtonsoft.Json
  • Microsoft.Extensions.Configuration.Json

Solution 4 - C#

I know that the question has an accepted answer but the question is about class libraries and the way to read appsettings.json from a classlibrary is the following:

Create a model that has the properties that will match those in your settings file:

public class ConfigurationManager
{
    public string BaseUrl { get; set; }
}

Add the actual settings in your appsettings.json

  "ConfigurationManager": {
    "BaseUrl": "myValue"
  }

Now register the appsettings.json section with your model in startup.cs:

 services.Configure<ConfigurationManager>(Configuration.GetSection("ConfigurationManager"));

In your class library create a class that is using

using Microsoft.Extensions.Options;

And get your configuration settings :

using Microsoft.Extensions.Options;
    

public class KeyUrls: IKeyUrls
{
    public string BaseUrl = "";
    private readonly IOptions<ConfigurationManager> _configurationService;

    public KeyUrls(IOptions<ConfigurationManager> configurationservice)
    {
        _configurationService = configurationservice;
        BaseUrl = _configurationService.Value.BaseUrl;
    }

    public  string GetAllKeyTypes()
    {
        return $"{BaseUrl}/something";
    }

    public  string GetFilteredKeys()
    {
        return $"{BaseUrl}/something2";
    }
}

For further details check This

Solution 5 - C#

It's easy to do that

string c = Directory.GetCurrentDirectory();
IConfigurationRoot configuration = 
newConfigurationBuilder().SetBasePath(c).AddJsonFile("appsettings.json").Build();
string connectionStringIs = configuration.GetConnectionString("MyConnection"); 

From the last line you can get connection string

if you want to configure the context, write the extra following code:

optionsBuilder.UseSqlServer(connectionStringIs); //inside protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

don't forget to install and use these packages:-

using Microsoft.Extensions.Configuration; 
using Microsoft.Extensions.Configuration.FileExtensions; 
using Newtonsoft.Json; 
using Microsoft.Extensions.Configuration.Json; 
using System.IO;

Solution 6 - C#

Solution 7 - C#

Directory.SetCurrentDirectory(AppContext.BaseDirectory);
var builder = new ConfigurationBuilder().SetBasePath (  Path.Combine(Directory.GetCurrentDirectory())   )
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncpr43View Question on Stackoverflow
Solution 1 - C#Stephen P.View Answer on Stackoverflow
Solution 2 - C#Clint BView Answer on Stackoverflow
Solution 3 - C#Carlos FernándezView Answer on Stackoverflow
Solution 4 - C#ThunD3eRView Answer on Stackoverflow
Solution 5 - C#Ahmed MohammedView Answer on Stackoverflow
Solution 6 - C#Gerson MoraesView Answer on Stackoverflow
Solution 7 - C#SanajView Answer on Stackoverflow