简体   繁体   中英

Access configuration through dependency injection in .NET Core console application

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

尝试在实例化 ServiceCollection 后立即添加

serviceCollection.AddOptions();

Please see this link having a great answer which works for " Access from class library to appsetting.json in Asp.net-core " https://stackoverflow.com/a/39548459/966557?stw=2 . It worked for my application.

But please note that I am not sure whether it is applicable for Console based app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM