Esempio n. 1
0
        /// <summary>
        /// Configure external API services that should be made available through the <see cref="IHttpClientFactory"/>.
        /// <para>Also configures an <seealso cref="IHealthCheck"/> for the API service.</para>
        /// <example>Configuration
        /// <code>
        /// "ApiServices": [
        ///    {
        ///     "Name": "FakeService",
        ///     "BaseUrl": "https://jsonplaceholder.typicode.com",
        ///     "HealthCheckUrlPath": "todos/1"
        ///    }
        ///  ]
        /// </code>
        /// <para>Name is used to identify the service in the <see cref="IHttpClientFactory"/>.</para>
        /// <para>BaseUrl is used to initialize the HttpClient.</para>
        /// <para>HealthCheckUrlPath is used to run the <see cref="IHealthCheck"/>.</para>
        /// </example>
        /// </summary>
        /// <param name="services"></param>
        /// <param name="hcBuilder"></param>
        private void ConfigureApiServices(IServiceCollection services, IHealthChecksBuilder hcBuilder)
        {
            var apiServices = Configuration.GetSection(ApiServicesConfigSectionKey).Get <List <ApiService> >() ?? new List <ApiService>();

            foreach (var api in apiServices)
            {
                if (!String.IsNullOrWhiteSpace(api.Name) && !String.IsNullOrWhiteSpace(api.BaseUrl))
                {
                    services.AddHttpClient(api.Name, c =>
                    {
                        c.BaseAddress = new Uri(api.BaseUrl);
                        c.Timeout     = TimeSpan.FromSeconds(15);
                    }).SetHandlerLifetime(TimeSpan.FromMinutes(5));

                    if (!String.IsNullOrWhiteSpace(api.HealthCheckPath))
                    {
                        hcBuilder.AddHttpHealthCheck(api.Name, api.HealthCheckPath);
                    }
                }
            }
        }