I have console app, where I have console app project and class library
I create appSettings.json file, where I store all data.
In console app I create this code in Program.cs
to work with envVariables
class Program
{
public static IConfigurationRoot Configuration;
private static ServiceThread _serviceThread;
static async Task Main(string[] args)
{
MainAsync(args).Wait();
// Run with console or service
var asService = !(Debugger.IsAttached || args.Contains("--console"));
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) => { services.AddHostedService<MonitoringService>(); });
builder.UseEnvironment(asService ? EnvironmentName.Production : EnvironmentName.Development);
if (asService)
{
await builder.RunAsServiceAsync();
}
else
{
_serviceThread = new ServiceThread();
_serviceThread.Start("Started");
await builder.RunConsoleAsync();
}
}
static async Task MainAsync(string[] args)
{
// Create service collection
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
// Create service provider
IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
// Print connection string to demonstrate configuration object is populated
Console.WriteLine(Configuration.GetConnectionString("DataConnection"));
}
private static void ConfigureServices(IServiceCollection serviceCollection)
{
// Build configuration
Configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
.AddJsonFile("appSettings.json", false)
.Build();
// Add access to generic IConfigurationRoot
serviceCollection.AddSingleton<IConfigurationRoot>(Configuration);
}
}
Now in class library I want to work with those variables.
I tried like this
public class HelpersAppService
{
private readonly IConfigurationRoot _configuration;
public HelpersAppService(IConfigurationRoot configuration)
{
_configuration = configuration;
}
public ServerUrlsDto GetServerUrls()
{
var serverUrls = _configuration.GetSection("ServerUrls").Get<ServerUrlsDto>();
return serverUrls;
}
public AuthDto GetAuth()
{
var authData = _configuration.GetSection("Auth").Get<AuthDto>();
return authData;
}
}
But problem, that I have null configuration in this method. What I'm doing wrong?