Ya no tienes que buscar más en otras páginas ya que has llegado al sitio justo, poseemos la respuesta que buscas y sin liarte.
Ejemplo 1: use appsettings.json en la aplicación de consola
All that’s required is to add the following NuGet packages and an appsettings.json file.Microsoft.Extensions.ConfigurationMicrosoft.Extensions.Configuration.FileExtensionsMicrosoft.Extensions.Configuration.JsonThe appsettings.json files “Copy to OutputDirectory” property should also be set to “Copy if newer” so that the application is able to access it when published.
Ejemplo 2: aplicación de consola .net core read appsettings.json
classProgrampublicstaticIConfigurationRoot configuration;static int Main(string[] args)// Initialize serilog loggerLog.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 collectionLog.Information("Creating service collection");ServiceCollection serviceCollection =newServiceCollection();ConfigureServices(serviceCollection);// Create service providerLog.Information("Building service provider");IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();// Print connection string to demonstrate configuration object is populatedConsole.WriteLine(configuration.GetConnectionString("DataConnection"));tryLog.Information("Starting service");await serviceProvider.GetService<App>().Run();Log.Information("Ending service");catch(Exception ex)Log.Fatal(ex,"Error running service");throw ex;finallyLog.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>();
Nos encantaría que puedieras compartir esta división si te valió la pena.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)