I am familiar w/ loading an appsettings.json section into a strongly typed object in .NET Core startup.cs. For example:
public class CustomSection
{
public int A {get;set;}
public int B {get;set;}
}
//In Startup.cs
services.Configure<CustomSection>(Configuration.GetSection("CustomSection"));
//Inject an IOptions instance
public HomeController(IOptions<CustomSection> options)
{
var settings = options.Value;
}
I have an appsettings.json section who's key/value pairs will vary in number and name over time. Therefore, it's not practical to hard code property names in a class since new key/value pairs would require a code change in the class. A small sample of some key/value pairs:
"MobileConfigInfo": {
"appointment-confirmed": "We've booked your appointment. See you soon!",
"appointments-book": "New Appointment",
"appointments-null": "We could not locate any upcoming appointments for you.",
"availability-null": "Sorry, there are no available times on this date. Please try another."
}
Is there a way to load this data into a MobileConfigInfo Dictionary object and then use the IOptions pattern to inject MobileConfigInfo into a controller?
I use the way below:
appsettings.json:
startup.cs:
Usage:
The only thing that worked for me (ASP.NET Core 3.0) was to add the following to the
ConfigureServices
method ofStartup.cs
:Go with this structure format:
Make your setting class look like this:
then do this
As an example of more complex binding in ASP.Net Core 2.1; I found using the
ConfigurationBuilder
.Get<T>()
method far easier to work with, as per the documention.I bound the configuration in my
Startup
method.This binds the
appsettings
file:Into this configuration structure:
For simple (perhaps microservice) applications you can just add it it as a singleton
Dictionary<string, string>
and then inject it wherever you need it:And the usage:
By far the simplest method would be to define your configuration class to inherit from the Dictionary type you want to support.
Then your startup and dependency injection support would be exactly the same as for any other configuration type.