Refactor database connection handling and update Docker Compose environment variables #5

This commit is contained in:
Marek Lesko
2025-07-28 10:05:41 +00:00
parent 75e43c7473
commit c8fde6f44c
3 changed files with 19 additions and 18 deletions

View File

@@ -39,8 +39,13 @@ namespace Api
}); });
builder.Services.AddControllers(); builder.Services.AddControllers();
// Add DbContext with SQL Server // Add DbContext with SQL Server
// Allow connection string to be set via environment variable (e.g., in Docker)
var envConnectionString = Environment.GetEnvironmentVariable("DB_CONNECTION_STRING");
var connectionString = !string.IsNullOrWhiteSpace(envConnectionString)
? envConnectionString
: builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options => builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); options.UseSqlServer(connectionString));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();

View File

@@ -1,17 +1,12 @@
{ {
/* "Authentication": {
The following identity settings need to be configured "PocketId": {
before the project can be successfully executed. "Authority": "https://identity.lesko.me",
For more info see https://aka.ms/dotnet-template-ms-identity-platform "ClientId": "21131567-fea1-42a2-8907-21abd874eff8",
*/ "ClientSecret": "a633GE6G3JoY8WopnsxhSXQpmsTuXa63",
"AzureAd": { "CallbackPath": "/signin-pocketid",
"Instance": "https://login.microsoftonline.com/", "Scopes": "openid profile email"
"Domain": "qualified.domain.name", }
"TenantId": "22222222-2222-2222-2222-222222222222",
"ClientId": "11111111-1111-1111-11111111111111111",
"Scopes": "access_as_user",
"CallbackPath": "/signin-oidc"
}, },
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {

View File

@@ -6,14 +6,15 @@ services:
depends_on: depends_on:
- db - db
restart: unless-stopped restart: unless-stopped
environment:
- ASPNETCORE_ENVIRONMENT=Production
- ConnectionStrings__DefaultConnection=Server=localhost;Database=centrum;User Id=sa;Password=$DB_PASSWORD;
network_mode: host network_mode: host
ports:
- "5000:5000"
db: db:
image: mcr.microsoft.com/mssql/server:2019-latest image: mcr.microsoft.com/mssql/server:2019-latest
restart: unless-stopped restart: unless-stopped
network_mode: host network_mode: host
environment: environment:
SA_PASSWORD: P@ssw0rd SA_PASSWORD: $DB_PASSWORD
ACCEPT_EULA: Y ACCEPT_EULA: Y