Search code examples
c#asp.net-core.net-core

Using IConfiguration in C# Class Library


I am building a class library using C# and .NET Core. I am trying to use configuration from a config.json file. Here are the contents of that file:

config.json

{
  "emailAddress":"[email protected]"
}

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()
  {
    // This is the approach I had been using since .NET 2.0:
    // return ConfigurationManager.AppSettings["emailAddress"];
    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!


Solution

  • 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.