-
Notifications
You must be signed in to change notification settings - Fork 10
/
Startup.cs
86 lines (73 loc) · 3.21 KB
/
Startup.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Net.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Polly;
using Polly.Extensions.Http;
using Polly.Registry;
using SimmyDemo_WebApi.Chaos;
namespace SimmyDemo_WebApi
{
public class Startup
{
public const string ResiliencePolicy = "ResiliencePolicy";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddMvcOptions(options => options.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
// Read the endpoints we expect the service to monitor.
services.Configure<MonitoringSettings>(Configuration.GetSection("MonitoringEndpoints"));
// Create (and register with DI) a policy registry containing some policies we want to use.
services.AddPolicyRegistry(new PolicyRegistry
{
{ ResiliencePolicy, GetResiliencePolicy() }
});
// Register a typed client via HttpClientFactory, set to use the policy we placed in the policy registry.
services.AddHttpClient<ResilientHttpClient>(client =>
{
client.Timeout = TimeSpan.FromSeconds(5);
})
.AddPolicyHandlerFromRegistry(ResiliencePolicy);
// Add ability for the app to populate ChaosSettings from json file (or any other .NET Core configuration source)
services.Configure<AppChaosSettings>(Configuration.GetSection("ChaosSettings"));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
// Only add Simmy chaos injection in development-environment runs (ie prevent chaos-injection ever reaching staging or prod - if that is what you want).
if (env.IsDevelopment())
{
// Wrap every policy in the policy registry in Simmy chaos injectors.
var registry = app.ApplicationServices.GetRequiredService<IPolicyRegistry<string>>();
registry?.AddChaosInjectors();
}
app.UseHttpsRedirection();
app.UseMvc();
}
private IAsyncPolicy<HttpResponseMessage> GetResiliencePolicy()
{
// Define a policy which will form our resilience strategy. These could be anything. The settings for them could obviously be drawn from config too.
var retry = HttpPolicyExtensions.HandleTransientHttpError()
.RetryAsync(2);
return retry;
}
}
}