I'm trying to implement dependency injection in a .net core console application, but I can't manage to configure MySettings
public static class Program
{
public static IConfigurationRoot Configuration { get; private set; }
public static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true)
Configuration = builder.Build();
var serviceProvider = BuildDi(Configuration);
serviceProvider.GetRequiredService<Bootstrapper>().DoThings();
}
private static IServiceProvider BuildDi(IConfigurationRoot configuration)
{
var services = new ServiceCollection();
services.Configure<MySettings>(configuration.GetSection("MySettings"));
services.AddSingleton<Bootstrapper>();
return services.BuildServiceProvider();
}
}
MySettings class is as easy as
public class MySettings
{
public string MyVariable { get; set; }
}
while appsettings.json is
{
"MySettings": {
"MyVariable": "test"
}
}
and Bootstrapper is
public class Bootstrapper
{
private readonly MySettings _settings;
public Bootstrapper(IOptions<MySettings> settings)
{
_settings = settings.Value;
}
public void DoThings()
{
Console.WriteLine(_settings.MyVariable);
}
}
but, when i'm trying to access Mysettings.MyVariable, i get null.
I can't understand what am I missing, since I have no problem doing the same exact thing in a asp.net core type project.
(yes, it's kinda like Access configuration through dependency injection in .NET Core console application, but with some steps further)