When I create a .NET Core console application, an appsettings.json file is not included like it is with an ASP.NET Core application.
Typically, the configuration is injected into the constructor of a class. However, with console applications, dependency injection is not configured by default. So we need to add a few lines of code to accomplish this.
var host = Host.CreateDefaultBuilder()
.ConfigureServices((context, services) => {
services.AddTransient<IDoSomethingService, DoSomethingService>();
})
.Build();
var svc = ActivatorUtilities.CreateInstance<DoSomethingService>(host.Services);
svc.Generate();
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
class DoSomethingService : IDoSomethingService
{
private IConfiguration _config;
public DoSomethingService(IConfiguration config)
{
_config = config;
}
public void Generate()
{
System.Console.WriteLine("Generate is running.");
System.Console.WriteLine(_config.GetConnectionString("Test"));
}
}
{
"ConnectionStrings": {
"Test": "TEST_CONNECTION_STRING"
}
}