Search code examples
c#.net-coreconsole.net-5asp.net-core-5.0

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


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?


Solution

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