首页 > 解决方案 > 使用 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

标签: c#asp.net-core.net-coreasp.net-core-webapi

解决方案


如果您使用扩展方法来注册您的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>设置。


推荐阅读