📌  相关文章
📜  .net core 读取 appsettings.json 控制台应用程序 - C# 代码示例

📅  最后修改于: 2022-03-11 14:49:16.349000             🧑  作者: Mango

代码示例2
class Program
{
    public static IConfigurationRoot configuration;

    static int Main(string[] args)
    {
        // Initialize serilog logger
        Log.Logger = new LoggerConfiguration()
             .WriteTo.Console(Serilog.Events.LogEventLevel.Debug)
             .MinimumLevel.Debug()
             .Enrich.FromLogContext()
             .CreateLogger();

        try
        {
            // Start!
            MainAsync(args).Wait();
            return 0;
        }
        catch
        {
            return 1;
        }
    }

    static async Task MainAsync(string[] args)
    {
        // Create service collection
        Log.Information("Creating service collection");
        ServiceCollection serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);

        // Create service provider
        Log.Information("Building service provider");
        IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();

        // Print connection string to demonstrate configuration object is populated
        Console.WriteLine(configuration.GetConnectionString("DataConnection"));

        try
        {
            Log.Information("Starting service");
            await serviceProvider.GetService().Run();
            Log.Information("Ending service");
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Error running service");
            throw ex;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    private static void ConfigureServices(IServiceCollection serviceCollection)
    {
        // Add logging
        serviceCollection.AddSingleton(LoggerFactory.Create(builder =>
        {
            builder
                .AddSerilog(dispose: true);
        }));

        serviceCollection.AddLogging();

        // Build configuration
        configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
            .AddJsonFile("appsettings.json", false)
            .Build();

        // Add access to generic IConfigurationRoot
        serviceCollection.AddSingleton(configuration);

        // Add app
        serviceCollection.AddTransient();
    }
}