47

I am creating a WPF project using .net Core 3.0, and I am having trouble adding the item appsettings.json file to my project which is to be used to store my DB connection string.

I would normally have done inside the app.config, but this has now been removed from .net Core.

Everywhere mentions using appsettings.json as a replacement, and that it has to be maunally added & initialised in the OnStartUp() function using an instance of IConfiguration, and there after using Dependency Injection to pass in the config class into the project.

But my issue is that can only add the appsettings.json item on asp.net Core projects? not my WPF solution.

I do apologies if I'm missing something very obvious (which I probably am), I just can't seem to find any solutions.

5 Answers 5

71

Steps:

  • To Add the following nuget packages

      Microsoft.Extensions.Configuration
      Microsoft.Extensions.Configuration.FileExtensions
      Microsoft.Extensions.Configuration.Json
      Microsoft.Extensions.DependencyInjection
    
  • You would need to create and add appsettings.json manually and set copy it to output directory as copy if newer


AppSetting.json

   {
  "ConnectionStrings": {
    "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
  },
}

Program.cs (For .NetCore Console App)

static void Main(string[] args)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

    IConfigurationRoot configuration = builder.Build();

    Console.WriteLine(configuration.GetConnectionString("BloggingDatabase"));
}

App.xaml.cs (For .NET CORE WPF)

public partial class App : Application
{
    public IServiceProvider ServiceProvider { get; private set; }
 
    public IConfiguration Configuration { get; private set; }
 
    protected override void OnStartup(StartupEventArgs e)
    {
        var builder = new ConfigurationBuilder()
         .SetBasePath(Directory.GetCurrentDirectory())
         .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
 
        Configuration = builder.Build();

      Console.WriteLine(Configuration.GetConnectionString("BloggingDatabase"));    

        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);
 
        ServiceProvider = serviceCollection.BuildServiceProvider();
 
        var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
        mainWindow.Show();
    }
 
    private void ConfigureServices(IServiceCollection services)
    {
        // ...
 
        services.AddTransient(typeof(MainWindow));
    }
}

References:

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for you answer but my issue is regarding WPF not ASP.Net unless i am missing somthing. When i click add on my WPF solution, I thought I would be able to add the file Appsettings.json? similar to how you would add a new class librray. but it doesnt appear when searched for
yes but have you tried add the json file manually and checking it ?
Updated answer for better clarity, for WPF and Console .Net Core
Appologies, I thought I had marked it as the answer. I have know.
Also, do remove the StartupUri from App.xaml since we are overriding mainWindow and showing it manually. also to avoid running the app twice as one will throw errors in case of DI configuration.
|
17

It's no requirement to switch to an appsettings.json file in .NET Core. You may still use the very same "old" XML-based App.config file in a WPF app that targets .NET Core if you want to.

Just add a new configuration file (Project->Add New Item->Application Configuration File) to your project and name it "App.config". If you then add the following contents to it:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <connectionStrings>
    <add name="connectionString" connectionString="..."/>
  </connectionStrings>
</configuration>

...you should be able to get the connection string at runtime using the ConfigurationManager API:

ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;

The default WPF template should include the System.Configuration.ConfigurationManager package by default.

1 Comment

Agreed. Microsoft still seem to be touting the App.Config method for WPF applications even under .Net Core. learn.microsoft.com/en-us/ef/core/miscellaneous/…
5

I found a short way.

  1. Install package Microsoft.Extensions.Configuration.Json

  2. Create AppSetting.json in solution

    {
        "ConnectionStrings": 
        {
            "MyDataBase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
        }
    }
    
  3. Create method GetConnectionString

    public string GetConnectionString(string connectionStringName)
    {
        var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                            .AddJsonFile("appsettings.json",
                                         optional: false,
                                         reloadOnChange: true);
    
        var configurationRoot = builder.Build();
    
        var connectionString = configurationRoot.GetConnectionString(connectionStringName);
        return connectionString;
    }
    
  4. Call method GetConnectionString in OnConfiguring

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        var connectionString = GetConnectionString("MyDataBase");
        optionsBuilder.UseLazyLoadingProxies().UseSqlServer(connectionString);
    }
    

Comments

4

add an App.config file to the root of your project and add this code:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <connectionStrings>
    <add name="AppConnectionString" connectionString="YourCS"/>
  </connectionStrings>

  <appSettings>
    <add key="DefaultLanguage" value="1"/>
  </appSettings>

</configuration>

appSettings is with S not s

Now you can read these anywhere of your dotnet core wpf app:

string DefaultLanguage = ConfigurationManager.AppSettings.Get("DefaultLanguage"); 
string ConnectionString = ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.