在类库中获取环境变量(.NET Core控制台应用程序)

我有控制台应用程序,在这里有控制台应用程序项目和类库

我创建了appSettings.json文件,在其中存储了所有数据。

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);
    }
}

现在在类库中,我想使用这些变量。

我尝试过这样

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;
        }
    }

但问题是,我在此方法中没有配置。我做错了什么?

评论