通过.NET Core控制台应用程序中的依赖项注入访问配置 [英] Access configuration through dependency injection in .NET Core console application

查看:330
本文介绍了通过.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://stackoverflow.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://stackoverflow.com/a/39548459/966557?stw=2. It worked for my application.

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

这篇关于通过.NET Core控制台应用程序中的依赖项注入访问配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆