Skip to content

Commit ad73e3a

Browse files
authored
Refactor database configuration and health checks
1 parent 541b39c commit ad73e3a

File tree

1 file changed

+66
-51
lines changed

1 file changed

+66
-51
lines changed

src/Web/Program.cs

Lines changed: 66 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +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+
122
var builder = WebApplication.CreateBuilder(args);
223
builder.Logging.AddConsole();
324

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"));
25+
if (builder.Environment.IsDevelopment() || builder.Environment.EnvironmentName == "Docker"){
26+
// Configure SQL Server (local)
27+
Microsoft.eShopWeb.Infrastructure.Dependencies.ConfigureServices(builder.Configuration, builder.Services);
1428
}
15-
else
16-
{
17-
// Real SQL Server (Azure) - opcional si decides usar SQL real
18-
var credential = new ChainedTokenCredential(new AzureDeveloperCliCredential(), new DefaultAzureCredential());
19-
builder.Configuration.AddAzureKeyVault(new Uri(builder.Configuration["AZURE_KEY_VAULT_ENDPOINT"] ?? ""), credential);
20-
21-
builder.Services.AddDbContext<CatalogContext>(c =>
22-
{
23-
var connectionString = builder.Configuration[builder.Configuration["AZURE_SQL_CATALOG_CONNECTION_STRING_KEY"] ?? ""];
24-
c.UseSqlServer(connectionString, sqlOptions => sqlOptions.EnableRetryOnFailure());
25-
});
26-
27-
builder.Services.AddDbContext<AppIdentityDbContext>(options =>
28-
{
29-
var connectionString = builder.Configuration[builder.Configuration["AZURE_SQL_IDENTITY_CONNECTION_STRING_KEY"] ?? ""];
30-
options.UseSqlServer(connectionString, sqlOptions => sqlOptions.EnableRetryOnFailure());
31-
});
29+
else{
30+
// Configure SQL Server (prod)
31+
Microsoft.eShopWeb.Infrastructure.Dependencies.ConfigureServices(builder.Configuration, builder.Services);
3232
}
33-
// ---------------------------------------------------------
3433

3534
builder.Services.AddCookieSettings();
35+
3636
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
3737
.AddCookie(options =>
3838
{
@@ -44,31 +44,36 @@
4444
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
4545
.AddDefaultUI()
4646
.AddEntityFrameworkStores<AppIdentityDbContext>()
47-
.AddDefaultTokenProviders();
47+
.AddDefaultTokenProviders();
4848

4949
builder.Services.AddScoped<ITokenClaimsService, IdentityTokenClaimService>();
5050
builder.Configuration.AddEnvironmentVariables();
5151
builder.Services.AddCoreServices(builder.Configuration);
5252
builder.Services.AddWebServices(builder.Configuration);
5353

54+
// Add memory cache services
5455
builder.Services.AddMemoryCache();
5556
builder.Services.AddRouting(options =>
5657
{
58+
// Replace the type and the name used to refer to it with your own
59+
// IOutboundParameterTransformer implementation
5760
options.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
5861
});
5962

6063
builder.Services.AddMvc(options =>
6164
{
62-
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
63-
});
65+
options.Conventions.Add(new RouteTokenTransformerConvention(
66+
new SlugifyParameterTransformer()));
6467

68+
});
6569
builder.Services.AddControllersWithViews();
6670
builder.Services.AddRazorPages(options =>
6771
{
6872
options.Conventions.AuthorizePage("/Basket/Checkout");
6973
});
7074
builder.Services.AddHttpContextAccessor();
71-
builder.Services.AddHealthChecks()
75+
builder.Services
76+
.AddHealthChecks()
7277
.AddCheck<ApiHealthCheck>("api_health_check", tags: new[] { "apiHealthCheck" })
7378
.AddCheck<HomePageHealthCheck>("home_page_health_check", tags: new[] { "homePageHealthCheck" });
7479
builder.Services.Configure<ServiceConfig>(config =>
@@ -77,11 +82,18 @@
7782
config.Path = "/allservices";
7883
});
7984

85+
// blazor configuration
8086
var configSection = builder.Configuration.GetRequiredSection(BaseUrlConfiguration.CONFIG_NAME);
8187
builder.Services.Configure<BaseUrlConfiguration>(configSection);
8288
var baseUrlConfig = configSection.Get<BaseUrlConfiguration>();
83-
builder.Services.AddScoped<HttpClient>(s => new HttpClient { BaseAddress = new Uri(baseUrlConfig!.WebBase) });
8489

90+
// Blazor Admin Required Services for Prerendering
91+
builder.Services.AddScoped<HttpClient>(s => new HttpClient
92+
{
93+
BaseAddress = new Uri(baseUrlConfig!.WebBase)
94+
});
95+
96+
// add blazor services
8597
builder.Services.AddBlazoredLocalStorage();
8698
builder.Services.AddServerSideBlazor();
8799
builder.Services.AddScoped<ToastService>();
@@ -93,6 +105,7 @@
93105
var app = builder.Build();
94106

95107
app.Logger.LogInformation("App created...");
108+
96109
app.Logger.LogInformation("Seeding Database...");
97110

98111
using (var scope = app.Services.CreateScope())
@@ -114,7 +127,6 @@
114127
}
115128
}
116129

117-
// ------------------- APP PIPELINE -------------------
118130
var catalogBaseUrl = builder.Configuration.GetValue(typeof(string), "CatalogBaseUrl") as string;
119131
if (!string.IsNullOrEmpty(catalogBaseUrl))
120132
{
@@ -125,29 +137,35 @@
125137
});
126138
}
127139

128-
app.UseHealthChecks("/health", new HealthCheckOptions
129-
{
130-
ResponseWriter = async (context, report) =>
140+
app.UseHealthChecks("/health",
141+
new HealthCheckOptions
131142
{
132-
var result = new
143+
ResponseWriter = async (context, report) =>
133144
{
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-
145+
var result = new
146+
{
147+
status = report.Status.ToString(),
148+
errors = report.Entries.Select(e => new
149+
{
150+
key = e.Key,
151+
value = Enum.GetName(typeof(HealthStatus), e.Value.Status)
152+
})
153+
}.ToJson();
154+
context.Response.ContentType = MediaTypeNames.Application.Json;
155+
await context.Response.WriteAsync(result);
156+
}
157+
});
142158
if (app.Environment.IsDevelopment() || app.Environment.EnvironmentName == "Docker")
143159
{
160+
app.Logger.LogInformation("Adding Development middleware...");
144161
app.UseDeveloperExceptionPage();
145162
app.UseShowAllServicesMiddleware();
146163
app.UseMigrationsEndPoint();
147164
app.UseWebAssemblyDebugging();
148165
}
149166
else
150167
{
168+
app.Logger.LogInformation("Adding non-Development middleware...");
151169
app.UseExceptionHandler("/Error");
152170
app.UseHsts();
153171
}
@@ -161,16 +179,13 @@
161179
app.UseAuthentication();
162180
app.UseAuthorization();
163181

182+
164183
app.MapControllerRoute("default", "{controller:slugify=Home}/{action:slugify=Index}/{id?}");
165184
app.MapRazorPages();
166185
app.MapHealthChecks("home_page_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("homePageHealthCheck") });
167186
app.MapHealthChecks("api_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("apiHealthCheck") });
187+
//endpoints.MapBlazorHub("/admin");
168188
app.MapFallbackToFile("index.html");
169189

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-
175190
app.Logger.LogInformation("LAUNCHING");
176191
app.Run();

0 commit comments

Comments
 (0)