Custom Configuration with Dependency Injection In 4 Steps

This article is about how to add and use custom configuration settings in a .Net Core App with Dependency Injection.

In my example I am setting various data access information in the app settings that I may or may not need in the depths of my application.

Step 1 – Add The Configuration

Add your custom configuration to the appsettings.json file, like so…

{
  "DataAccessConfiguration": {
    "BarForecastDBConectionString": "",
    "CacheDurationHours": 2,
    "OceanForecastApiDetails": {
      "Url": "https://thedevmill.nz/GetOceanForecasts",
      "ApiKey": "apiKey"
    },
    "TideApiDetails": {
      "Url": "https://thedevmill.nz/GetTides",
      "ApiKey": "apiKey"
    },
    "RiverFlowApiDetails": {
      "Url": "https://thedevmill.nz/GetRiverFlows",
      "UserName": "User Name",
      "Password": "Password"
    }
  },
  ...
}

Step 2 – Create Your Classes

Create the classes that represent the json objects in your appsettings.

    public class DataAccessConfiguration
    {
        public string BarForecastDBConectionString { get; set; }
        public int CacheDurationHours { get; set; }
        public ApiDetails OceanForecastApiDetails { get; set; }
        public ApiDetails TideApiDetails { get; set; }
        public ApiDetails RiverFlowApiDetails { get; set; }
    }

    public class ApiDetails
    {
        public string Url { get; set; }
        public string ApiKey { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }

Step 3 – Register The Configuration

Depending on your configuration, this will either go in you Program.cs or the Startup.cs, but whatever that might be, it goes where you register your services.

My example was built in a .Net 6.0 MVC Web Application.

builder.Services
.Configure<DataAccessConfiguration>(builder.Configuration.GetSection("DataAccessConfiguration"));

Step 4 – Setup the Class to Receive the Configuration

For this example I pass them straight through to the Controller, but in reality I would add it to the constructor of some logic class that may use them.

    public class HomeController : Controller
    {
        private readonly DataAccessConfiguration _dbAccessConfig;

        public HomeController (IOptions<DataAccessConfiguration> dbAccessConfig)
        {
            _dbAccessConfig = dbAccessConfig.Value;
        }
    }

Run the application with a break point on the method above and the settings will be there.

Leave a Reply

Your email address will not be published. Required fields are marked *