El tutorial o código que verás en este artículo es la solución más eficiente y válida que hallamos a esta duda o problema.
Ejemplo: aplicación de consola .net core read appsettings.json
classProgrampublicstaticIConfigurationRoot configuration;staticintMain(string[] args)// Initialize serilog logger
Log.Logger =newLoggerConfiguration().WriteTo.Console(Serilog.Events.LogEventLevel.Debug).MinimumLevel.Debug().Enrich.FromLogContext().CreateLogger();try// Start!MainAsync(args).Wait();return0;catchreturn1;staticasyncTaskMainAsync(string[] args)// Create service collection
Log.Information("Creating service collection");ServiceCollection serviceCollection =newServiceCollection();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<App>().Run();
Log.Information("Ending service");catch(Exception ex)
Log.Fatal(ex,"Error running service");throw ex;finally
Log.CloseAndFlush();privatestaticvoidConfigureServices(IServiceCollection serviceCollection)// Add logging
serviceCollection.AddSingleton(LoggerFactory.Create(builder =>
builder
.AddSerilog(dispose:true);));
serviceCollection.AddLogging();// Build configuration
configuration =newConfigurationBuilder().SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName).AddJsonFile("appsettings.json",false).Build();// Add access to generic IConfigurationRoot
serviceCollection.AddSingleton<IConfigurationRoot>(configuration);// Add app
serviceCollection.AddTransient<App>();
valoraciones y reseñas
Si te gusta la informática, eres capaz de dejar una división acerca de qué te ha gustado de este enunciado.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)