c# - 使用 ASP.NET CORE API 显式访问选项实例并将其传递给 ConfigureServices 中的方法
问题描述
我需要将 IOptions 的实例作为参数传递给方法,如下所示:知道吗?
services.SetWaitAndRetryPolicy<CustomHttpClient>(); //how to retrieve and pass instance of IOptions<MyConfig>
我点击下面和底部的链接:
如何从 ASP.NET Core 中的 .json 文件中读取 AppSettings 值
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
services.SetWaitAndRetryPolicy<CustomHttpClient>(); //how to retrieve and pass instance of IOptions<MyConfig>
}
public static class IServiceCollectionExtension
{
public static void SetWaitAndRetryPolicy<T>(this IServiceCollection services, IOptions<MyConfig> config) where T : class
{
}
}
如何在 asp.net core 中获取 IConfiguration 的实例?
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2
ASP.NET 核心 2.2
解决方案
如果您使用扩展方法来注册您的CustomHttpClient
类,那么您可以访问配置方法中的选项。
public static class IServiceCollectionExtension
{
public static void SetWaitAndRetryPolicy<T>(this IServiceCollection services) where T : class
{
services.AddHttpClient<T>((sp, client) =>
{
var options = sp.GetService<IOptions<MyConfig>>();
...
});
}
}
配置操作的参数之一是IServiceProvider
. 从这里您可以访问任何已注册的服务,在本例中为IOptions<MyConfig>
设置。
推荐阅读
- r - 如何遍历R中数据框中的列?
- node.js - 无法在 nodeJS 服务器上实现 HTTPS
- python - 如何去除python中base64编码字符串的噪声?
- java - 从 List 中特定键的所有值生成字符串
- react-native - 如何在 React Native 中使用单例模式
- python - 'chromedriver' 可执行文件需要在 PATH 中。将 chromedriver 添加到我的 PATH 后
- ruby-on-rails - 为什么我会收到此 Ruby on Rails 错误?:#index 缺少请求格式的模板:text/html
- r - 使用 Tidyverse 和 fitdistrplus 进行批量分布拟合
- composer-php - PHPUnit 找不到我的类,但 composer.json 中的自动加载看起来不错
- css - 容器部分之外的图像