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

问题描述 投票:0回答:2

我有一些来自 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>();
    }
}

以及正在做这项工作的班级:

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 具有其依赖性?

c# .net-core console .net-5 asp.net-core-5.0
2个回答
18
投票

尝试以这种方式添加 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
}

0
投票

试试这个…

dotnet new install JandaBox
dotnet new consolebox -n MyApp

更多信息请参阅https://www.nuget.org/packages/JandaBox/

© www.soinside.com 2019 - 2024. All rights reserved.