-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
408 lines (327 loc) · 15.2 KB
/
Program.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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Asp.Versioning.ApiExplorer;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MoreLinq;
using OneBeyond.Studio.Application.SharedKernel.DependencyInjection;
using OneBeyond.Studio.Application.SharedKernel.DomainEvents;
using OneBeyond.Studio.Crosscuts.Logging;
using OneBeyond.Studio.Crosscuts.Options;
using OneBeyond.Studio.Crosscuts.Utilities.Templating;
using OneBeyond.Studio.DataAccess.EFCore.DependencyInjection;
using OneBeyond.Studio.EmailProviders.Folder.DependencyInjection;
using OneBeyond.Studio.EmailProviders.SendGrid.DependencyInjection;
using OneBeyond.Studio.FileStorage.Azure.DependencyInjection;
using OneBeyond.Studio.FileStorage.Azure.Options;
using OneBeyond.Studio.FileStorage.FileSystem.DependencyInjection;
using OneBeyond.Studio.FileStorage.FileSystem.Options;
using OneBeyond.Studio.FileStorage.Infrastructure.DependencyInjection;
using OneBeyond.Studio.Hosting.AspNet.ModelBinders.MixedSource.DependencyInjection;
using OneBeyond.Studio.Infrastructure.Azure.KeyVault.Configurations;
using OneBeyond.Studio.Infrastructure.Azure.MessageQueues.DependencyInjection;
using OneBeyond.Studio.Infrastructure.Azure.MessageQueues.Options;
using OneBeyond.Studio.Obelisk.Application;
using OneBeyond.Studio.Obelisk.Application.DependencyInjection;
using OneBeyond.Studio.Obelisk.Application.Services.AmbientContexts;
using OneBeyond.Studio.Obelisk.Authentication.Application.DependencyInjection;
using OneBeyond.Studio.Obelisk.Authentication.Application.Services.ApplicationClaims;
using OneBeyond.Studio.Obelisk.Infrastructure.Data;
using OneBeyond.Studio.Obelisk.Infrastructure.Data.Seeding;
using OneBeyond.Studio.Obelisk.Infrastructure.DependencyInjection;
using OneBeyond.Studio.Obelisk.WebApi;
using OneBeyond.Studio.Obelisk.WebApi.AmbientContexts;
using OneBeyond.Studio.Obelisk.WebApi.Extensions;
using OneBeyond.Studio.Obelisk.WebApi.Helpers;
using OneBeyond.Studio.Obelisk.WebApi.HostedServices;
using OneBeyond.Studio.Obelisk.WebApi.Middlewares.ExceptionHandling;
using OneBeyond.Studio.Obelisk.WebApi.Middlewares.Security;
using OneBeyond.Studio.Obelisk.WebApi.Swagger;
using Serilog;
using Swashbuckle.AspNetCore.SwaggerGen;
using FolderEmailSender = OneBeyond.Studio.EmailProviders.Folder;
using SendGridEmailSender = OneBeyond.Studio.EmailProviders.SendGrid;
namespace OneBeyond.Studio.Obelisk.WebApi;
public static class Program
{
private const string _selfCheck = "self";
public static async Task Main(string[] args)
{
// Logger used during app bootstrap
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
try
{
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
?? throw new Exception("The ASPNETCORE_ENVIRONMENT variable is not set.");
Log.Information("Obelisk starting up using environment: {RunTimeEnvironment}", environmentName);
var builder = WebApplication.CreateBuilder(args);
ConfigureConfiguration(builder.Configuration, environmentName);
ConfigureLogging(builder.Host);
builder.Host.ConfigureServices(ConfigureServices);
// Autofac factory will automatically populate services defined above into its container
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(ConfigureAutofacServices);
var app = builder.Build();
ConfigureMiddleware(app, app.Services, builder.Configuration);
await app.InitialiseAsync(builder.Environment, CancellationToken.None);
await app.SeedAsync(CancellationToken.None);
await app.RunAsync();
}
catch (Exception exception)
when (exception is not HostAbortedException) // Used by EF migration building process
{
Log.Fatal(exception, "Obelisk web host terminated unexpectedly");
}
finally
{
Log.Information("Obelisk shut down complete");
Log.CloseAndFlush();
}
}
private static void ConfigureConfiguration(ConfigurationManager configuration, string environmentName)
=> configuration
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environmentName}.json", optional: true)
.AddKeyVault("KeyVault")
.AddEnvironmentVariables()
.AddUserSecrets(Assembly.GetExecutingAssembly());
private static void ConfigureLogging(IHostBuilder builder)
=> builder.UseSerilog(
(context, loggerConfig) => loggerConfig.ReadFrom.Configuration(context.Configuration));
private static void ConfigureServices(HostBuilderContext hostBuilderContext, IServiceCollection services)
{
var configuration = hostBuilderContext.Configuration;
var environment = hostBuilderContext.HostingEnvironment;
services.AddOptions();
services.AddSignalR();
// This is required in order to restore telemetry collection. Azure agent-based collection
// stops working as soon as AI SDK gets referenced from the project which is needed for logging to AI.
services.AddApplicationInsightsTelemetry(
(options) => options.ConnectionString = configuration.GetValue<string>("APPLICATIONINSIGHTS_CONNECTION_STRING"));
if (environment.IsDevelopment())
{
services.AddEmailSender(
configuration.GetOptions<FolderEmailSender.Options.EmailSenderOptions>("EmailSender:Folder"));
}
else
{
services.AddEmailSender(
configuration.GetOptions<SendGridEmailSender.Options.EmailSenderOptions>("EmailSender:SendGrid"));
}
services.AddHttpContextAccessor();
if (!environment.IsDevelopment())
{
services.AddHttpsRedirection(
(options) =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443;
});
}
services.Configure<ClientApplicationOptions>(configuration.GetSection("ClientApplication"));
services.AddTransient<ClientApplicationLinkGenerator, ClientApplicationLinkGenerator>();
services.AddTransient<ITemplateRenderer, HandleBarsTemplateRenderer>();
services.AddTransient<IApplicationClaimsService, ApplicationClaimsIdentityFactory>();
services.AddApplicationAuthentication(environment, configuration)
.AddUserStore<AuthUserStore>() //Used for JWT authentication
.AddClaimsPrincipalFactory<ApplicationClaimsIdentityFactory>()
.AddEntityFrameworkStores<DomainContext>();
if (!environment.IsDevelopment())
{
services.AddAntiforgery(
(options) =>
{
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
}
services.AddControllers()
.AddNewtonsoftJson(
(options) =>
{
options.AddPrivateSettersSerialization();
});
var apiVersioningBuilder = services.AddApiVersioning(
(options) =>
{
options.AssumeDefaultVersionWhenUnspecified = false;
options.ReportApiVersions = true;
});
apiVersioningBuilder.AddApiExplorer(
(options) =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
services.AddCors(
(options) =>
{
options.AddDefaultPolicy(
(builder) =>
{
var origins = configuration
.GetOptions<string[]>("Cors:AllowedOrigins")
.Select(origin => origin.TrimEnd('/')) //trim ending slash for urls (to eliminate CORS issues)
.ToArray();
builder.WithOrigins(origins)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
services.Configure<ApiBehaviorOptions>(
(options) =>
{
options.SuppressInferBindingSourcesForParameters = true;
});
services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(
Assembly.GetExecutingAssembly(),
typeof(AssemblyMark).Assembly,
typeof(Authentication.Application.AssemblyMark).Assembly));
services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
services.AddSwaggerGen();
services.AddDataAccessSeeding(
configuration.GetOptions<IdentitiesSeederOptions>("Identities:Seeding"));
services.AddDataAccess(
configuration,
(dataAccessBuilder) =>
dataAccessBuilder
.WithDomainEvents(isReceiverHost: true)); // If DE support is enabled, make sure the DomainContextFactory does also when constructing the DomainContext.
//.WithUnitOfWork();
services.AddHostedService<DomainEventRelayJob>();
services.AddEntityTypeProjections(typeof(Infrastructure.AssemblyMark).Assembly);
services.AddAutoMapper(typeof(AssemblyMark).Assembly);
services.AddFileStorage(
(builder) =>
_ = environment.IsDevelopment()
? builder.UseFileSystem(configuration.GetOptions<FileSystemFileStorageOptions>("FileStorage:FileSystem"))
: builder.UseAzureBlobs(configuration.GetOptions<AzureBlobFileStorageOptions>("FileStorage:AzureBlobStorage")));
services.AddMixedSourceBinder(); //Mixed source binder used to gather commands, queries and dtos in controllers from mixed sources: body and route
services.AddLocalization(options => options.ResourcesPath = "Localizations/Resources");
services.AddHealthChecks(environment, configuration);
}
private static IServiceCollection AddHealthChecks(
this IServiceCollection services,
IHostEnvironment environment,
IConfiguration configuration)
{
var hcBuilder = services.AddHealthChecks();
hcBuilder.AddCheck(_selfCheck, () => HealthCheckResult.Healthy());
hcBuilder
.AddSqlServer(
configuration.GetConnectionString("ApplicationConnectionString")!,
name: "DB-check",
tags: new string[] { "db" });
hcBuilder
.AddAzureQueueStorage(
configuration.GetOptions<AzureMessageQueueOptions>("DomainEvents:Queue").ConnectionString!,
name: "queue-check",
tags: new string[] { "queue" });
if (!environment.IsDevelopment())
{
hcBuilder
.AddAzureBlobStorage(
configuration.GetOptions<AzureBlobFileStorageOptions>("FileStorage:AzureBlobStorage").ConnectionString!,
name: "storage-check",
tags: new string[] { "storage" });
}
return services;
}
private static void ConfigureAutofacServices(HostBuilderContext hostBuilderContext, ContainerBuilder containerBuilder)
{
var configuration = hostBuilderContext.Configuration;
containerBuilder.AddAmbientContextAccessor<AmbientContextAccessor, AmbientContext>();
containerBuilder.AddApplication();
containerBuilder.AddAuthApplication();
containerBuilder.AddAzureMessageQueue<RaisedDomainEvent>(
configuration.GetOptions<AzureMessageQueueOptions>("DomainEvents:Queue"));
}
private static void ConfigureMiddleware(
IApplicationBuilder app,
IServiceProvider services,
IConfiguration configuration)
{
var loggerFactory = services.GetRequiredService<ILoggerFactory>();
LogManager.Configure(loggerFactory);
app.UseSerilogRequestLogging();
var environment = services.GetRequiredService<IWebHostEnvironment>();
app.UseCookiePolicy(
new CookiePolicyOptions
{
Secure = environment.IsDevelopment()
? CookieSecurePolicy.SameAsRequest
: CookieSecurePolicy.Always
});
if (environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSecurityHeadersMiddleware(
new SecurityHeadersBuilder()
.AddSecurityPolicyFromConfiguration(configuration.GetSection("SecurityHeaders")));
app.UseUnhandledExceptionLogging();
app.UseErrorResultGenerator();
app.UseExceptionHandling();
app.UseStaticFiles();
app.UseRouting();
//app.UseUnitOfWork();
app.UseCors();
var cultures = configuration.GetOptions<string[]>("Localization:SupportedCultures");
if (cultures.Any())
{
app.UseRequestLocalization(
new RequestLocalizationOptions()
.SetDefaultCulture(cultures.First())
.AddSupportedCultures(cultures)
.AddSupportedUICultures(cultures));
}
app.UseAuthentication();
app.UseAuthorization();
app.UseSwagger();
app.UseSwaggerUI(
(options) =>
{
var provider = services.GetRequiredService<IApiVersionDescriptionProvider>();
foreach (var description in provider.ApiVersionDescriptions)
{
options.SwaggerEndpoint(
$"/swagger/{description.GroupName}/swagger.json",
$"{SwaggerConstants.APITitle} {description.GroupName.ToUpperInvariant()}");
// Set Swagger UI as the homepage
options.RoutePrefix = string.Empty;
}
});
app.UseEndpoints(
(endpoints) =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("/health/ready", new HealthCheckOptions()
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
endpoints.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = r => r.Name.Contains(_selfCheck)
});
});
}
}