Esempio n. 1
0
        public async Task HttpClientFactory_ApplyMultiplePolicies()
        {
            IServiceCollection services = new ServiceCollection();

            ///// ADD HTTP CLIENT VIA HTTPCLIENTFACTORY AND POLICIES
            // this would typically happen in Startup.ConfigureServices
            // using a named client, can specify a <TClient> to inject it into a specific class

            // setup circuit breaker seperately so you can maintain a pointer to it for testing (validate state, reset, etc)
            var circuitBreakerPolicy = DemoPolicyFactory.GetHttpCircuitBreakerPolicy();
            ICircuitBreakerPolicy <HttpResponseMessage> circuitBreakerPointer = (ICircuitBreakerPolicy <HttpResponseMessage>)circuitBreakerPolicy;

            services.AddHttpClient("CustomerService",
                                   client =>
            {
                client.BaseAddress = new Uri(DemoHelper.DemoBaseUrl);
                client.Timeout     =
                    TimeSpan.FromSeconds(
                        3);         // this will apply as an outer timeout to the entire request flow, including waits, retries,etc
            })

            // add policies from outer (1st executed) to inner (closest to dependency call)
            // all policies must implement IASyncPolicy
            .AddPolicyHandler(DemoPolicyFactory.GetHttpFallbackPolicy("Default!"))
            .AddPolicyHandler(DemoPolicyFactory.GetHttpRetryPolicy())
            .AddPolicyHandler(circuitBreakerPolicy)
            .AddPolicyHandler(DemoPolicyFactory.GetHttpInnerTimeoutPolicy());

            ///// TEST POLICIES /////
            await VerifyResiliencyPolicies(services, circuitBreakerPointer);
        }
Esempio n. 2
0
        public async Task HttpClientFactory_OnlyApplyPolicyToGetRequests()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddHttpClient("CustomerService",
                                   client =>
            {
                client.BaseAddress = new Uri(DemoHelper.DemoBaseUrl);
                client.Timeout     =
                    TimeSpan.FromSeconds(3);
            })
            .AddPolicyHandler(request =>
                              request.Method == HttpMethod.Get
                        ? DemoPolicyFactory.GetHttpRetryPolicy()
                        : Policy.NoOpAsync <HttpResponseMessage>());
            var serviceProvider = services.BuildServiceProvider();
            var clientFactory   = serviceProvider.GetService <IHttpClientFactory>();
            var httpClient      = clientFactory.CreateClient("CustomerService");

            var responseMessage = await httpClient.GetAsync("api/demo/error?failures=1");

            Assert.IsTrue(responseMessage.IsSuccessStatusCode);
        }