Access configuration through dependency injection in .NET Core console application

♀尐吖头ヾ 提交于 2019-12-10 21:19:43

问题


How do I properly Activate a configuration that was added using the ServiceCollection.Configure function ?

     public static void Main(args[] args)
     { 
        serviceCollection = new ServiceCollection();
        serviceCollection .Configure<MyOptions>(Configuration.GetSection("options"));
        Services = serviceCollection.BuildServiceProvider();

        ActivatorUtilities.CreateInstance<MyOptions>(Services);
        ActivatorUtilities.CreateInstance<SomeClassThatNeedsoptions>(Services);
     }


 public SomeClassThatNeedsoptions(IOptions<MyOptions> options)
 {
     _options = options.Value;
 }

On the 2nd ActivatorUtilities.CreateInstance I get the following error

Unable to resolve service for type 'Microsoft.Extensions.Options.IOptions [MyOptions]`

I am writing this in a console application and from what I understand am manually injecting the dependencies using the ActivatorUtilities class. I seem to be able to do it with services added with AddSingleton but not with services added with .Configure


回答1:


Try adding right after you instantiate ServiceCollection

serviceCollection.AddOptions();


来源:https://stackoverflow.com/questions/40081594/access-configuration-through-dependency-injection-in-net-core-console-applicati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!