user70192 user70192 - 2 months ago 28
C# Question

Using IConfiguration in C# Class Library

I am building a class library using C# and Core .NET. I am trying to use configuration from a

config.json
file. Here are the contents of that file:

config.json

{
"emailAddress":"someone@somewhere.com"
}


In an attempt to use
config.json
for my configuration, I'm referencing
Microsoft.Framework.ConfigurationModel.Json
in my
project.json
file. In my code, I have the following:

MyClass.cs

using Microsoft.Framework.ConfigurationModel;
public class MyClass
{
public string GetEmailAddress()
{
// return ConfigurationManager.AppSettings["emailAddress"]; This is the approach I had been using since .NET 2.0
return ?; // What goes here?
}
}


Since .NET 2.0, I had been using
ConfigurationManager.AppSettings["emailAddress"]
. However, I'm now trying to learn how to do it the new way via
IConfiguration
. My problem is, this is a class library. For that reason, I'm not sure how, or where, or when, the configuration file gets loaded. In traditional .NET, I just needed to name a file web.config for ASP.NET projects and app.config for other projects. Now, I'm not sure. I have both an ASP.NET MVC 6 project and an XUnit project. So, I'm trying to figure out how to use
config.json
in both of these scenarios.

Thank you!

Answer

Never used it but a quick search lead me to this...

    var configuration = new Configuration();
    configuration.AddJsonFile(“config.json”);
    var emailAddress = configuration.Get("emailAddress");

Maybe you could try that.