namespace Bts.Extensions.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using System.Diagnostics; public static class HostBuilderExtensions { public static IHostBuilder CreateBtsBuilder(string[] args) { // Obtain calling assembly name here, rather than in the lambda where it is actually needed, // because want the name of the assembly that called this function, not the assembly that will eventually invoke // the lambda...that will be the Microsoft.Extensions.Hosting assembly. // Get the name of the assembly that called this function. That will act as the "appsettings" // json file prefix var exeName = GetCallingAssemblyName(); return Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((context, configBuilder) => ConfigureApp(configBuilder, context.HostingEnvironment.EnvironmentName, exeName)); } public static void ConfigureApp(IConfigurationBuilder configBuilder, string? environment = null, string? prefix = null) { var baseFileName = prefix is null ? "appsettings" : $"{prefix}.appsettings"; AddJsonFile($"{baseFileName}.json"); if (environment is not null) { AddJsonFile($"{baseFileName}.{environment}.json"); } var cfg = configBuilder.Build().GetSection("config")?.Value; if (!SetBasePath(cfg)) { AddJsonFile(cfg); } bool SetBasePath(string? path) { if (!Directory.Exists(path)) { return false; } configBuilder.SetBasePath(path); return true; } bool AddJsonFile(string? path) { if (!File.Exists(path)) { return false; } configBuilder.AddJsonFile(path); return true; } } public static string GetCallingAssemblyName() => new StackTrace() .GetFrame(2) ?.GetMethod() ?.Module ?.Assembly ?.GetName() ?.Name ?? throw new InvalidOperationException("Failed to determine name of calling assembly (calling method is null)"); }