如何在控制台应用程序中获取用于依赖注入的 IConfiguration

How to Get An IConfiguration For Dependency Injection In A Console App

我有一些来自 Asp.Net Core 5 Web 应用程序的代码,我想从控制台应用程序调用这些代码。

一切顺利,但我有一个问题尚未找到解决方案。鉴于控制台主要代码:

class Program
{
    static void Main(string[] args)
    {
        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);
        var serviceProvider = serviceCollection.BuildServiceProvider();

        serviceProvider.GetService<CodeGen>().Generate();
    }

    private static void ConfigureServices(IServiceCollection serviceCollection)
    {
        var configurationRoot = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appSettings.json", false)
            .Build();

        serviceCollection.AddOptions();
        serviceCollection.Configure<AppSettings>(configurationRoot.GetSection("Configuration"));

        // add services
        serviceCollection.AddScoped<IDataRepo, DataRepo>()
                         .AddScoped<CodeGen>();
    }
}

而正在工作的class:

public class CodeGen
{
    private readonly IDataRepo _dataRepo;
    private readonly AppSettings _appSettings;

    public CodeGen(IDataRepo dataRepo, AppSettings appSettings)
    {
        _dataRepo    = dataRepo;
        _appSettings = appSettings;
    }

    public void Generate()
    {
        Console.WriteLine("Generates code... ");

        CodeGenWordRules.Init(_appSettings.OutputFolder, _dataRepo);
    }
}

问题是 DataRepo 构造函数依赖于 IConfiguration。

public DataRepo(IConfiguration configuration, ICodeGenManager codeGenManager)

如何从 IConfigurationRoot 获取 IConfiguration 并将其添加到 serviceCollection 以便 DataRepo 具有它的依赖性?

试试这样添加IConfiguration

private  static void ConfigureServices(IServiceCollection services)
{
        IConfiguration configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appSettings.json", false)
        .Build();
            
        services.AddSingleton<IConfiguration>(configuration);
        .... another DI
}