3
votes

I need Guidance or explanation of how appsettings works in .net core I've 2 project api and dataacess(classlib) if each one have appsettings.json and both have connection string section. when I read the connection string from the dataaccess project it reads the value from the hosting app which is the api , so how appsettings work when i build a project that uses other classlib project that has also appsettings file, does this merge at the build output or does the hosting app override the classlib or the classlib setting are totally ignored ? appreciate your guidance

1

1 Answers

0
votes

Here is how I read connection string using Configuration pattern of ASP.Net Core

You can read my full code here and Microsoft doc

Before we start to do anything make sure we install 2 package for our console applicaiton because I also want to read some setting in appSetting.json

Install-Package Microsoft.Extensions.Options
Install-Package Microsoft.Extensions.DependencyInjection

Inside our Program.cs file

public static void Main()
    {
        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);

        // create service provider
        var serviceProvider = serviceCollection.BuildServiceProvider();

        // entry to run app
        serviceProvider.GetService<WebJob>().RunQueue();
        serviceProvider.GetService<WebJob>().Run();
        Console.ReadLine();
    }

    private static void ConfigureServices(IServiceCollection serviceCollection)
    {
          var currentDir = ProjectPath.GetApplicationRoot();

         // build configuration
         varconfiguration = newConfigurationBuilder()
                   .SetBasePath(currentDir)
                   .AddJsonFile("appsettings.json",false)
                   .Build();

         serviceCollection.AddOptions();
         serviceCollection.Configure<WebJobSettings>(configuration.GetSection("WebJobSettings"));
         // add app
         serviceCollection.AddTransient<WebJob>();
    }

public class WebJob
{
  private readonly IOptions<WebJobSettings> _webJobSettings;
  public WebJob(
    IOptions<WebJobSettings> webJobSettings)
  {
    _webJobSettings = webJobSettings;
  } 
  public void Run()
  {


 GlobalConfiguration.Configuration.UseSqlServerStorage(_webJobSettings.Value.DbConnectionString); // here is how I access the config

     using(var server = new BackgroundJobServer())
     {
        Console.WriteLine("Hangfire Server started. Press any key to exit...");
        Console.ReadLine();
     }
  }
}