通过.NET Core控制台应用程序中的依赖项注入访问配置

通过.NET Core控制台应用程序中的依赖项注入访问配置

问题描述:

如何正确激活使用ServiceCollection.Configure函数添加的配置?

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;
 }

在第二个ActivatorUtilities.CreateInstance上,我收到以下错误

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


无法解析 Microsoft.Extensions.Options.IOptions [MyOptions]类型的服务

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

我正在控制台应用程序中编写此代码,据我了解,我是使用ActivatorUtilities类手动注入依赖项。我似乎能够使用AddSingleton添加的服务来实现,但不能使用.Configure添加的服务来实现。

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

请参见此链接有一个很好的答案,适用于 从类库访问Asp.net-core中的appsetting.json https://*.com/a/39548459/966557?stw=2
它适用于我的应用程序。

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

但是请注意,我不确定它是否适用于基于控制台的应用程序。