【问题标题】:How appsetting.json works in multiple project .net core?appsetting.json 如何在多个项目 .net 核心中工作?
【发布时间】:2020-01-17 20:06:14
【问题描述】:

我需要有关 appsettings 如何在 .net core 中工作的指导或解释 我有 2 个项目 api 和 dataacess(classlib) 如果每个都有 appsettings.json 并且都有连接字符串部分。当我从数据访问项目中读取连接字符串时,它会从托管应用程序(即 api)中读取值,因此当我构建一个使用其他类库项目的项目时,appsettings 是如何工作的,该项目也具有 appsettings 文件,在构建输出中是否合并还是托管应用程序覆盖类库或类库设置被完全忽略?感谢您的指导

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    这是我使用 ASP.Net Core 的配置模式读取连接字符串的方法

    你可以阅读我的完整代码here和微软doc

    在我们开始做任何事情之前,请确保我们为我们的控制台应用程序安装了 2 个包,因为我还想阅读 appSetting.json 中的一些设置

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

    在我们的 Program.cs 文件中

    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();
         }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-01
      • 2022-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多