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?
.Configure<AppSettings>(...)
will register anIOptions<AppSettings>
service instance. But yourCodeGen
service expects anAppSettings
.