Loading external JSON files into IConfiguration #30451
-
My Apologies if this is answered elsewhere, my Google-foo is not with me today I've got a series of
calls to load external, lets call them user settings in json files that may or may not exist at the next app launch. I want them available in the IConfiguration instance returned from DI so I have them loading in MauiProgram.cs which works fine in debug mode but as soon as i flip it to release i'm getting constant InvalidOperationException and FileSystem.AppDataDirectory is what is throwing it. I get that that stuff might not be available in MauiProgram.cs but when else can I load these JSON files and ensure when I drop an IConfiguration in a class constructor I can .Get<>() the values from those external json files. Edit I appreciate the responses so far, but it seems I'm not getting to the answer I'm looking for I already have an embedded JSON file being loaded with
where This holds the application defaults for certain settings as a user uses the system certain settings can be overridden e.g. window position when overridden they are saved in the Finally when ever the program needs to "get" something from IConfiguration it calls one of these two extension methods depending on if the class name, or a custom string (in the case of common types like TimeSpan being used multiple times for different things) is the section name
it simply attempts to load the user override section first but if it does not find it then it rolls over to the default section automatically. Now when in debug i can see in the output it throwing In release mode it just crashes |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 9 replies
-
@TofuBug I asked CoPilot about it, then went to duck search, found relevant stackoverflow topic and maybe a potenial soluton on James blog. Does this help? |
Beta Was this translation helpful? Give feedback.
-
In your MauiProgram.cs, let's try registering the ConfigurationManager itself for DI, i.e. builder.Services.AddSingleton<Microsoft.Extensions.Configuration.IConfigurationManager>(builder.Configuration); Then, we can access the ConfigurationManager later, in, say, App.xaml.cs, and populate with late configurations: using Microsoft.Extensions.Configuration;
public partial class App : Application
{
public App(IConfigurationManager cm)
{
InitializeComponent();
// populate Name with something ...
cm.AddJsonFile($"{FileSystem.AppDataDirectory}/{Name}.json", true, true);
}
protected override Window CreateWindow(IActivationState? activationState)
{
return new Window(new AppShell());
}
} |
Beta Was this translation helpful? Give feedback.
In your MauiProgram.cs, let's try registering the ConfigurationManager itself for DI, i.e.
Then, we can access the ConfigurationManager later, in, say, App.xaml.cs, and populate with late configurations: