-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
179 lines (152 loc) · 6.55 KB
/
Program.cs
File metadata and controls
179 lines (152 loc) · 6.55 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
using Demo1.Middleware;
using Demo1.Telemetry;
using Demo1.Services;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.FeatureManagement;
using Azure.Identity;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddHealthChecks();
// ✅ 12-FACTOR: Register application services via dependency injection
builder.Services.AddSingleton<ISearchService, InMemorySearchService>();
builder.Services.AddSingleton<IWeatherService, MockWeatherService>();
builder.Services.AddSingleton<IUserProfileService, InMemoryUserProfileService>();
builder.Services.AddSingleton<IStyleGeneratorService, StyleGeneratorService>();
// ✅ 12-FACTOR: Configure distributed cache based on environment
var cacheProvider = builder.Configuration["CacheProvider"] ?? "Memory";
if (cacheProvider.Equals("Redis", StringComparison.OrdinalIgnoreCase))
{
var redisConnectionString = builder.Configuration["Redis:ConnectionString"]
?? Environment.GetEnvironmentVariable("REDIS_CONNECTIONSTRING")
?? "localhost:6379";
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = redisConnectionString;
options.InstanceName = "Demo1_";
});
}
else
{
builder.Services.AddDistributedMemoryCache();
}
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.Name = ".Demo1.Session";
});
// Flag set when Azure App Configuration provider is successfully added
var azureAppConfigRegistered = false;
// ✅ 12-FACTOR: Configuration from environment variables, not hardcoded
var appConfigEndpoint = Environment.GetEnvironmentVariable("AZUREAPPCONFIGURATION__ENDPOINT")
?? builder.Configuration["AzureAppConfiguration:Endpoint"];
var appConfigConnectionString = Environment.GetEnvironmentVariable("AZUREAPPCONFIGURATION__CONNECTIONSTRING")
?? builder.Configuration["AzureAppConfiguration:ConnectionString"];
var appConfigLabel = builder.Configuration["AzureAppConfiguration:Label"] ?? "";
if (!string.IsNullOrWhiteSpace(appConfigEndpoint) || !string.IsNullOrWhiteSpace(appConfigConnectionString))
{
try
{
if (!string.IsNullOrWhiteSpace(appConfigEndpoint))
{
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential())
.UseFeatureFlags(featureFlagOptions =>
{
featureFlagOptions.Label = appConfigLabel;
featureFlagOptions.SetRefreshInterval(TimeSpan.FromSeconds(30));
})
.ConfigureRefresh(refresh =>
{
refresh.Register("FeatureManagement:Sentinel", refreshAll: true)
.SetRefreshInterval(TimeSpan.FromSeconds(30));
});
});
azureAppConfigRegistered = true;
}
else if (!string.IsNullOrWhiteSpace(appConfigConnectionString))
{
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(appConfigConnectionString)
.UseFeatureFlags(featureFlagOptions =>
{
featureFlagOptions.Label = appConfigLabel;
featureFlagOptions.SetRefreshInterval(TimeSpan.FromSeconds(30));
})
.ConfigureRefresh(refresh =>
{
refresh.Register("FeatureManagement:Sentinel", refreshAll: true)
.SetRefreshInterval(TimeSpan.FromSeconds(30));
});
});
azureAppConfigRegistered = true;
}
}
catch (Exception ex)
{
Console.WriteLine($"Warning: Failed to configure Azure App Configuration: {ex.Message}");
Console.WriteLine("Azure App Configuration will be skipped. Feature flags will fallback to local config.");
}
}
// Add Feature Management
builder.Services.AddFeatureManagement();
// Ensure Azure App Configuration services are registered so the middleware can be used safely
builder.Services.AddAzureAppConfiguration();
// ✅ 12-FACTOR: Externalized Application Insights configuration
var appInsightsConnectionString = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS__CONNECTIONSTRING")
?? builder.Configuration["ApplicationInsights:ConnectionString"];
builder.Services.AddApplicationInsightsTelemetry(options =>
{
options.ConnectionString = appInsightsConnectionString;
});
// Configure sampling percentage
var samplingPercentage = builder.Configuration.GetValue<double?>("ApplicationInsights:SamplingPercentage") ?? 100.0;
builder.Services.Configure<Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration>(config =>
{
var samplingProcessorBuilder = config.DefaultTelemetrySink.TelemetryProcessorChainBuilder;
// Use fixed-rate sampling based on the configured percentage
samplingProcessorBuilder.UseSampling(samplingPercentage);
samplingProcessorBuilder.Build();
});
// Register custom telemetry initializers
builder.Services.AddSingleton<ITelemetryInitializer>(new CustomTelemetryInitializer("Demo1"));
var app = builder.Build();
// Flag set when Azure App Configuration provider is successfully added
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseSecurityHeaders();
app.UseStatusCodePagesWithReExecute("/Home/Error{0}");
app.UseRouting();
// 🔥 ANTI-PATTERN: Session middleware - kept for demo pages only
app.UseSession();
// Apply Azure App Configuration middleware so feature flags and config refresh are available per-request
if (azureAppConfigRegistered)
{
app.UseAzureAppConfiguration();
}
app.UseAuthorization();
app.MapStaticAssets();
app.MapHealthChecks("/health");
app.MapHealthChecks("/health/ready");
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}")
.WithStaticAssets();
app.Run();
/// <summary>
/// Marker partial class used to host the application in integration tests.
/// </summary>
public partial class Program
{
}