Felix Cartwright
Felix Cartwright

Reputation: 129

How to supply configuration from Web API to class library dependency

I've got a class library in the same solution as a Core Web API, and I need the library to be able to access some configuration app settings.

In the world of Console apps or Web Forms, I'd simply put those settings into app.config (for the console) or web.config (for the ASP.NET project) and rely on ConfigurationManager to do the math. However, I'm discovering that that doesn't work anymore in WebAPI.

For example, I've got the following controller...

    public class LabController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            TestUtility util = new TestUtility();
            string result = util.ConfigTest();

            return Ok( new { Message = result});           
        }
    }

which relies on the following class in a separate class library project...

    public class TestUtility
    {
        public string ConfigTest()
        {
            string result = "I can't reach the configuration.";

            try
            {
                result = ConfigurationManager.AppSettings["HomeAddress"].ToString();
            }
            catch (Exception) { }

            return result;
        }
    }

and here's the appsettings.json file...

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "HomeAddress": "123 Elm St."
}

The result coming back from the service is the config failure message, not the "123 Elm St." I want to make available in the class library. How do I make configuration settings in the main (WebAPI) project available to code in the class library?

Thanks.

Upvotes: 1

Views: 2171

Answers (1)

nsquires
nsquires

Reputation: 1119

If the 'TestUtility' class is registered in the DI container, you can inject the configuration into that class's constructor.

    public class TestUtility
    {
        private readonly string _homeAddress;
        
        public TestUtility(IConfiguration configuration) 
        { 
            _homeAddress = configuration["HomeAddress"]
        }

        public string ConfigTest()
        {
             return _homeAddress;
        }
    }

Upvotes: 1

Related Questions