Skip to content

Commit 541b39c

Browse files
authored
Refactor database setup and health check configuration
Refactor Program.cs to improve database configuration and health checks.
1 parent 5209b13 commit 541b39c

File tree

1 file changed

+39
-65
lines changed

1 file changed

+39
-65
lines changed

src/Web/Program.cs

Lines changed: 39 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,38 @@
1-
using System.Net.Mime;
2-
using Ardalis.ListStartupServices;
3-
using Azure.Identity;
4-
using BlazorAdmin;
5-
using BlazorAdmin.Services;
6-
using Blazored.LocalStorage;
7-
using BlazorShared;
8-
using Microsoft.AspNetCore.Authentication.Cookies;
9-
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
10-
using Microsoft.AspNetCore.Identity;
11-
using Microsoft.AspNetCore.Mvc.ApplicationModels;
12-
using Microsoft.EntityFrameworkCore;
13-
using Microsoft.eShopWeb;
14-
using Microsoft.eShopWeb.ApplicationCore.Interfaces;
15-
using Microsoft.eShopWeb.Infrastructure.Data;
16-
using Microsoft.eShopWeb.Infrastructure.Identity;
17-
using Microsoft.eShopWeb.Web;
18-
using Microsoft.eShopWeb.Web.Configuration;
19-
using Microsoft.eShopWeb.Web.HealthChecks;
20-
using Microsoft.Extensions.Diagnostics.HealthChecks;
21-
221
var builder = WebApplication.CreateBuilder(args);
232
builder.Logging.AddConsole();
243

25-
if (builder.Environment.IsDevelopment() || builder.Environment.EnvironmentName == "Docker"){
26-
// Configure SQL Server (local)
27-
Microsoft.eShopWeb.Infrastructure.Dependencies.ConfigureServices(builder.Configuration, builder.Services);
4+
// -------------------- DATABASE CONFIG --------------------
5+
bool useInMemoryDb = builder.Environment.IsDevelopment() ||
6+
builder.Environment.EnvironmentName == "Docker" ||
7+
bool.TryParse(builder.Configuration["UseInMemoryDatabase"], out var result) && result;
8+
9+
if (useInMemoryDb)
10+
{
11+
// In-memory database
12+
builder.Services.AddDbContext<CatalogContext>(c => c.UseInMemoryDatabase("CatalogDb"));
13+
builder.Services.AddDbContext<AppIdentityDbContext>(options => options.UseInMemoryDatabase("IdentityDb"));
2814
}
29-
else{
30-
// Configure SQL Server (prod)
15+
else
16+
{
17+
// Real SQL Server (Azure) - opcional si decides usar SQL real
3118
var credential = new ChainedTokenCredential(new AzureDeveloperCliCredential(), new DefaultAzureCredential());
3219
builder.Configuration.AddAzureKeyVault(new Uri(builder.Configuration["AZURE_KEY_VAULT_ENDPOINT"] ?? ""), credential);
20+
3321
builder.Services.AddDbContext<CatalogContext>(c =>
3422
{
3523
var connectionString = builder.Configuration[builder.Configuration["AZURE_SQL_CATALOG_CONNECTION_STRING_KEY"] ?? ""];
3624
c.UseSqlServer(connectionString, sqlOptions => sqlOptions.EnableRetryOnFailure());
3725
});
26+
3827
builder.Services.AddDbContext<AppIdentityDbContext>(options =>
3928
{
4029
var connectionString = builder.Configuration[builder.Configuration["AZURE_SQL_IDENTITY_CONNECTION_STRING_KEY"] ?? ""];
4130
options.UseSqlServer(connectionString, sqlOptions => sqlOptions.EnableRetryOnFailure());
4231
});
4332
}
33+
// ---------------------------------------------------------
4434

4535
builder.Services.AddCookieSettings();
46-
4736
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
4837
.AddCookie(options =>
4938
{
@@ -55,36 +44,31 @@
5544
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
5645
.AddDefaultUI()
5746
.AddEntityFrameworkStores<AppIdentityDbContext>()
58-
.AddDefaultTokenProviders();
47+
.AddDefaultTokenProviders();
5948

6049
builder.Services.AddScoped<ITokenClaimsService, IdentityTokenClaimService>();
6150
builder.Configuration.AddEnvironmentVariables();
6251
builder.Services.AddCoreServices(builder.Configuration);
6352
builder.Services.AddWebServices(builder.Configuration);
6453

65-
// Add memory cache services
6654
builder.Services.AddMemoryCache();
6755
builder.Services.AddRouting(options =>
6856
{
69-
// Replace the type and the name used to refer to it with your own
70-
// IOutboundParameterTransformer implementation
7157
options.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
7258
});
7359

7460
builder.Services.AddMvc(options =>
7561
{
76-
options.Conventions.Add(new RouteTokenTransformerConvention(
77-
new SlugifyParameterTransformer()));
78-
62+
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
7963
});
64+
8065
builder.Services.AddControllersWithViews();
8166
builder.Services.AddRazorPages(options =>
8267
{
8368
options.Conventions.AuthorizePage("/Basket/Checkout");
8469
});
8570
builder.Services.AddHttpContextAccessor();
86-
builder.Services
87-
.AddHealthChecks()
71+
builder.Services.AddHealthChecks()
8872
.AddCheck<ApiHealthCheck>("api_health_check", tags: new[] { "apiHealthCheck" })
8973
.AddCheck<HomePageHealthCheck>("home_page_health_check", tags: new[] { "homePageHealthCheck" });
9074
builder.Services.Configure<ServiceConfig>(config =>
@@ -93,18 +77,11 @@
9377
config.Path = "/allservices";
9478
});
9579

96-
// blazor configuration
9780
var configSection = builder.Configuration.GetRequiredSection(BaseUrlConfiguration.CONFIG_NAME);
9881
builder.Services.Configure<BaseUrlConfiguration>(configSection);
9982
var baseUrlConfig = configSection.Get<BaseUrlConfiguration>();
83+
builder.Services.AddScoped<HttpClient>(s => new HttpClient { BaseAddress = new Uri(baseUrlConfig!.WebBase) });
10084

101-
// Blazor Admin Required Services for Prerendering
102-
builder.Services.AddScoped<HttpClient>(s => new HttpClient
103-
{
104-
BaseAddress = new Uri(baseUrlConfig!.WebBase)
105-
});
106-
107-
// add blazor services
10885
builder.Services.AddBlazoredLocalStorage();
10986
builder.Services.AddServerSideBlazor();
11087
builder.Services.AddScoped<ToastService>();
@@ -116,7 +93,6 @@
11693
var app = builder.Build();
11794

11895
app.Logger.LogInformation("App created...");
119-
12096
app.Logger.LogInformation("Seeding Database...");
12197

12298
using (var scope = app.Services.CreateScope())
@@ -138,6 +114,7 @@
138114
}
139115
}
140116

117+
// ------------------- APP PIPELINE -------------------
141118
var catalogBaseUrl = builder.Configuration.GetValue(typeof(string), "CatalogBaseUrl") as string;
142119
if (!string.IsNullOrEmpty(catalogBaseUrl))
143120
{
@@ -148,35 +125,29 @@
148125
});
149126
}
150127

151-
app.UseHealthChecks("/health",
152-
new HealthCheckOptions
128+
app.UseHealthChecks("/health", new HealthCheckOptions
129+
{
130+
ResponseWriter = async (context, report) =>
153131
{
154-
ResponseWriter = async (context, report) =>
132+
var result = new
155133
{
156-
var result = new
157-
{
158-
status = report.Status.ToString(),
159-
errors = report.Entries.Select(e => new
160-
{
161-
key = e.Key,
162-
value = Enum.GetName(typeof(HealthStatus), e.Value.Status)
163-
})
164-
}.ToJson();
165-
context.Response.ContentType = MediaTypeNames.Application.Json;
166-
await context.Response.WriteAsync(result);
167-
}
168-
});
134+
status = report.Status.ToString(),
135+
errors = report.Entries.Select(e => new { key = e.Key, value = Enum.GetName(typeof(HealthStatus), e.Value.Status) })
136+
}.ToJson();
137+
context.Response.ContentType = MediaTypeNames.Application.Json;
138+
await context.Response.WriteAsync(result);
139+
}
140+
});
141+
169142
if (app.Environment.IsDevelopment() || app.Environment.EnvironmentName == "Docker")
170143
{
171-
app.Logger.LogInformation("Adding Development middleware...");
172144
app.UseDeveloperExceptionPage();
173145
app.UseShowAllServicesMiddleware();
174146
app.UseMigrationsEndPoint();
175147
app.UseWebAssemblyDebugging();
176148
}
177149
else
178150
{
179-
app.Logger.LogInformation("Adding non-Development middleware...");
180151
app.UseExceptionHandler("/Error");
181152
app.UseHsts();
182153
}
@@ -190,13 +161,16 @@
190161
app.UseAuthentication();
191162
app.UseAuthorization();
192163

193-
194164
app.MapControllerRoute("default", "{controller:slugify=Home}/{action:slugify=Index}/{id?}");
195165
app.MapRazorPages();
196166
app.MapHealthChecks("home_page_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("homePageHealthCheck") });
197167
app.MapHealthChecks("api_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("apiHealthCheck") });
198-
//endpoints.MapBlazorHub("/admin");
199168
app.MapFallbackToFile("index.html");
200169

170+
// ------------------- FORCE PORT -------------------
171+
var port = Environment.GetEnvironmentVariable("PORT") ?? "5000"; // Azure asigna PORT dinámicamente
172+
app.Urls.Clear();
173+
app.Urls.Add($"http://*:{port}");
174+
201175
app.Logger.LogInformation("LAUNCHING");
202176
app.Run();

0 commit comments

Comments
 (0)