You can use anything that is normally available from IConfiguration in a .net core WPF app. This example is from .net 8 with a standard Microsoft template but will work with older versions too.
One thing that the other answers are missing is being able to have local values in an appsettings.Development.json file that override the values in appsettings.json
First you must set up launch settings.
Go to your project properties => Debug => General => Open debug launch profiles UI. Add this environment variable: DOTNET_ENVIRONMENT with the value Development.
The Development value is only used for local debugging. If you publish you will use whatever the DOTNET_ENVIRONMENT value is on the machine, or the default of Production. Test this.
You'll see a new launchSettings.json file under the Properties folder.
{
"profiles": {
"WpfApp1": {
"commandName": "Project",
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}
Then set up the host builder. I am also registering dependency injection to make using the options from the app settings easy but it is not required.
App.xaml.cs
public partial class App : Application
{
public static IHost? Host { get; private set; }
public App()
{
Host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder()
.ConfigureServices(ConfigureServices)
.Build();
}
private void ConfigureServices(HostBuilderContext context, IServiceCollection services)
{
// Add for strongly typed options injected as IOptions<ExampleType>
services.AddOptions();
services.Configure<ExampleType>(context.Configuration);
// Or access the value directly here without injecting it.
ExampleType? appSettings = context.Configuration.Get<ExampleType>();
// Add Services
services.AddSingleton<IDataService, DataService>();
services.AddSingleton<MainWindow>();
}
protected override async void OnStartup(StartupEventArgs e)
{
await Host!.StartAsync();
var mainWindow = Host.Services.GetRequiredService<MainWindow>();
mainWindow.Show();
base.OnStartup(e);
}
protected override async void OnExit(ExitEventArgs e)
{
await Host!.StopAsync();
base.OnExit(e);
}
}
Simply add your appsettings.json and appsettings.Development.json files and you will have the same functionality as a .net core web app.