5

I have some code from a Asp.Net Core 5 web app that I want to call from a console application.

It's coming together but I have one issue that I have not yet found a solution to. Given the console main code:

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

And the class that is doing the work:

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

The problem is that the DataRepo constructor has a dependency on IConfiguration.

public DataRepo(IConfiguration configuration, ICodeGenManager codeGenManager)

How do I get the an IConfiguration from the IConfigurationRoot that I can add to the serviceCollection so that the DataRepo will have it's dependency?

WillC
  • 1,761
  • 17
  • 37

1 Answers1

12

Try to add IConfiguration this way

private  static void ConfigureServices(IServiceCollection services)
{
        IConfiguration configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appSettings.json", false)
        .Build();
            
        services.AddSingleton<IConfiguration>(configuration);
        .... another DI
}
Serge
  • 40,935
  • 4
  • 18
  • 45
  • Thought I had tried that! This seems to be working for getting the configuration, so thanks! – WillC Oct 27 '21 at 05:27