Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

570
Visualizações
Cannot add appsettings.json inside WPF project .net core 3.0

I am creating a WPF project using .net Core 3.00, 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 Dependancy 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 appolgies if I'm missing somthing very obvious (which I probally am), I just cant seem to find any solutions.

Many thanks in advance

over 4 years ago · Santiago Trujillo
4 Respostas
Responde à pergunta

0

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:

  • https://blog.bitscry.com/2017/05/30/appsettings-json-in-net-core-console-app/
  • https://marcominerva.wordpress.com/2019/03/06/using-net-core-3-0-dependency-injection-and-service-provider-with-wpf/
  • https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings
over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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;
over 4 years ago · Santiago Trujillo Relatório

0

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);
    }
    
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda