40

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Chaos
  • 633
  • 1
  • 6
  • 14

4 Answers4

64

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:

devklick
  • 2,000
  • 3
  • 30
  • 47
Clint
  • 6,011
  • 1
  • 21
  • 28
  • 2
    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 – Chaos Jan 25 '20 at 13:09
  • 1
    yes but have you tried add the json file manually and checking it ? – Clint Jan 25 '20 at 13:10
  • 2
    Updated answer for better clarity, for WPF and Console .Net Core – Clint Jan 25 '20 at 17:31
  • 2
    Appologies, I thought I had marked it as the answer. I have know. – Chaos Jan 30 '20 at 19:00
  • Don't forget for appsettings.json to mark Build Action as Content and Copy if Newer in Properties. – Snuffler_71 Aug 16 '21 at 07:41
  • 6
    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. – Ali Kleit Oct 06 '21 at 17:38
  • Future lookers, mark your appsettings.json to 'Copy always' from the properties window, or click on the file 'appsettings.json' from the solution explorer and hit F4 or properties Kudos to the original comment – Ameer Adel Jul 20 '22 at 10:44
  • I would highly recommend adding @AliKleit's comment to the answer, if only I'd read that it would have saved me hours of debugging – SulsDotK Jan 05 '23 at 16:19
  • To execute properly you must add the following attributes to your `.csproj` XML file : `Always` – gurkan Feb 05 '23 at 10:33
16

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.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • 1
    Agreed. Microsoft still seem to be touting the App.Config method for WPF applications even under .Net Core. https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-strings#winforms--wpf-applications – Caltor Sep 22 '20 at 11:41
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;
M Komaei
  • 7,006
  • 2
  • 28
  • 34
1

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);
    }
    
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92