无法获得依赖注入的配置<>在.net核心控制台应用程序中工作

时间:2018-03-07 08:50:06

标签: c# dependency-injection .net-core console-application

我试图在.net核心控制台应用程序中实现依赖注入,但我无法配置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类就像

一样简单
public class MySettings
{
    public string MyVariable { get; set; }        
}

而appsettings.json是

{
  "MySettings": {
    "MyVariable": "test"
  }
}

和Bootstrapper是

public class Bootstrapper
{
    private readonly MySettings _settings;

    public Bootstrapper(IOptions<MySettings> settings)
    {
        _settings = settings.Value;
    }

    public void DoThings()
    {
        Console.WriteLine(_settings.MyVariable);
    }
}

但是,当我试图访问Mysettings.MyVariable时,我得到null。

我无法理解我错过了什么,因为我在asp.net核心类型项目中做同样的事情没有问题。

(是的,它有点像Access configuration through dependency injection in .NET Core console application,但还有一些步骤)

0 个答案:

没有答案