0
votes

I need to pass instance of IOptions to a method as parameter, like below: any idea?

   services.SetWaitAndRetryPolicy<CustomHttpClient>(); //how to retrieve and pass instance of IOptions<MyConfig> 

I follow the links below and at the bottom:

How to read AppSettings values from .json file in ASP.NET Core

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
        {

        }
    }

How to get an instance of IConfiguration in asp.net core?

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2

ASP.NET CORE 2.2

1

1 Answers

2
votes

If you are using the extension method to register your CustomHttpClient class then you access the options within the configure method.

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>>();

            ...
        });
    }
}

One of the parameters to the configure action is the IServiceProvider. From here you can get access to any of the registered services, in this case the IOptions<MyConfig> settings.