Access configuration through dependency injection

2019-07-07 03:28发布

问题:

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