Skip to content

Commit bdde7e3

Browse files
committed
🧹refactor: modularize application startup configuration
- Refactored Program.cs to act as a thin orchestrator by moving complex startup logic into dedicated extension methods in AppConfiguration. - Centralized configuration for OpenTelemetry, JWT authentication, Redis cache and database migrations, improving readability, maintainability and adherence to SRP. - Database migration failures are now logged as fatal errors.
1 parent d501f51 commit bdde7e3

2 files changed

Lines changed: 79 additions & 62 deletions

File tree

EventFlow.Presentation/Config/AppConfiguration.cs

Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,13 @@
1212
using Microsoft.OpenApi.Models;
1313
using System.IO.Compression;
1414
using System.Text.Json.Serialization;
15+
using Microsoft.EntityFrameworkCore;
16+
using Microsoft.IdentityModel.Tokens;
17+
using System.Text;
18+
using Serilog;
19+
using OpenTelemetry.Resources;
20+
using OpenTelemetry.Trace;
21+
using OpenTelemetry.Exporter;
1522

1623
namespace EventFlow.Presentation.Config;
1724

@@ -109,9 +116,9 @@ public static IServiceCollection ConfigureSwagger(this IServiceCollection servic
109116

110117
options.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme);
111118
options.AddSecurityRequirement(new OpenApiSecurityRequirement
112-
{
119+
{
113120
{ securityScheme, Array.Empty<string>() }
114-
});
121+
});
115122
});
116123

117124
return services;
@@ -127,4 +134,65 @@ public static IServiceCollection AddRedisCacheConfig(this IServiceCollection ser
127134

128135
return services;
129136
}
137+
138+
public static IServiceCollection AddOpenTelemetryConfig(this IServiceCollection services)
139+
{
140+
services.AddOpenTelemetry()
141+
.ConfigureResource(resource => resource
142+
.AddService("EventFlow.API"))
143+
.WithTracing(tracing => tracing
144+
.AddAspNetCoreInstrumentation()
145+
.AddHttpClientInstrumentation()
146+
.AddEntityFrameworkCoreInstrumentation()
147+
.AddOtlpExporter(options =>
148+
{
149+
options.Endpoint = new Uri("http://eventflow-jaeger:4317");
150+
options.Protocol = OtlpExportProtocol.Grpc;
151+
}));
152+
153+
return services;
154+
}
155+
156+
public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration)
157+
{
158+
services
159+
.AddAuthentication("Bearer")
160+
.AddJwtBearer("Bearer", options =>
161+
{
162+
options.TokenValidationParameters = new TokenValidationParameters
163+
{
164+
ValidateIssuer = true,
165+
ValidateAudience = true,
166+
ValidateLifetime = true,
167+
ValidateIssuerSigningKey = true,
168+
ValidIssuer = configuration["Jwt:Issuer"],
169+
ValidAudience = configuration["Jwt:Audience"],
170+
IssuerSigningKey = new SymmetricSecurityKey(
171+
Encoding.UTF8.GetBytes(configuration["Jwt:Key"]!))
172+
};
173+
});
174+
175+
return services;
176+
}
177+
178+
public static void ApplyDatabaseMigrations(this IApplicationBuilder app)
179+
{
180+
using (var scope = app.ApplicationServices.CreateScope())
181+
{
182+
var services = scope.ServiceProvider;
183+
try
184+
{
185+
var context = services.GetRequiredService<EventFlowContext>();
186+
187+
if (context.Database.GetPendingMigrations().Any())
188+
{
189+
context.Database.Migrate();
190+
}
191+
}
192+
catch (Exception ex)
193+
{
194+
Log.Fatal(ex, "Ocorreu um erro ao aplicar as migrações automáticas.");
195+
}
196+
}
197+
}
130198
}

EventFlow.Presentation/Program.cs

Lines changed: 9 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
11
using EventFlow.Presentation.Config;
2-
using EventFlow.Infrastructure.Data;
3-
using Microsoft.IdentityModel.Tokens;
42
using Serilog;
5-
using OpenTelemetry.Resources;
6-
using OpenTelemetry.Trace;
7-
using OpenTelemetry.Exporter;
83

94
var builder = WebApplication.CreateBuilder(args);
105

@@ -13,64 +8,19 @@
138

149
AppConfiguration.ConfigureMvc(builder);
1510

16-
builder.Services.ConfigureSwagger();
17-
builder.Services.AddEndpointsApiExplorer();
18-
builder.Services.AddSwaggerGen();
19-
builder.Services.AddDbContextConfig(builder.Configuration, builder.Environment.IsDevelopment());
20-
builder.Services.AddRedisCacheConfig();
21-
22-
builder.Services.AddOpenTelemetry()
23-
.ConfigureResource(resource => resource
24-
.AddService("EventFlow.API"))
25-
.WithTracing(tracing => tracing
26-
.AddAspNetCoreInstrumentation()
27-
.AddHttpClientInstrumentation()
28-
.AddEntityFrameworkCoreInstrumentation()
29-
.AddOtlpExporter(options =>
30-
{
31-
options.Endpoint = new Uri("http://eventflow-jaeger:4317");
32-
options.Protocol = OtlpExportProtocol.Grpc;
33-
}));
34-
35-
builder.Services.AddDependencyInjectionConfig();
36-
3711
builder.Services
38-
.AddAuthentication("Bearer")
39-
.AddJwtBearer("Bearer", options =>
40-
{
41-
options.TokenValidationParameters = new TokenValidationParameters
42-
{
43-
ValidateIssuer = true,
44-
ValidateAudience = true,
45-
ValidateLifetime = true,
46-
ValidateIssuerSigningKey = true,
47-
ValidIssuer = builder.Configuration["Jwt:Issuer"],
48-
ValidAudience = builder.Configuration["Jwt:Audience"],
49-
IssuerSigningKey = new SymmetricSecurityKey(
50-
System.Text.Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
51-
};
52-
});
12+
.ConfigureSwagger()
13+
.AddEndpointsApiExplorer()
14+
.AddSwaggerGen()
15+
.AddDbContextConfig(builder.Configuration, builder.Environment.IsDevelopment())
16+
.AddRedisCacheConfig()
17+
.AddOpenTelemetryConfig()
18+
.AddDependencyInjectionConfig()
19+
.AddJwtAuthentication(builder.Configuration);
5320

5421
var app = builder.Build();
5522

56-
using (var scope = app.Services.CreateScope())
57-
{
58-
var services = scope.ServiceProvider;
59-
try
60-
{
61-
var context = services.GetRequiredService<EventFlowContext>();
62-
63-
if (context.Database.GetPendingMigrations().Any())
64-
{
65-
context.Database.Migrate();
66-
}
67-
}
68-
catch (Exception ex)
69-
{
70-
Log.Fatal(ex, "Ocorreu um erro ao aplicar as migrações automáticas.");
71-
}
72-
}
73-
23+
app.ApplyDatabaseMigrations();
7424
app.UseSerilogRequestLogging();
7525

7626
if (app.Environment.IsDevelopment())
@@ -79,7 +29,6 @@
7929
app.UseSwaggerUI();
8030
}
8131

82-
8332
app.UseAuthentication();
8433
app.UseAuthorization();
8534

0 commit comments

Comments
 (0)