Init
This commit is contained in:
53
Prefab.Catalog.Api/Data/AppDb.cs
Normal file
53
Prefab.Catalog.Api/Data/AppDb.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Prefab.Catalog.Domain.Entities;
|
||||
using Prefab.Data;
|
||||
using Prefab.Handler;
|
||||
|
||||
namespace Prefab.Catalog.Api.Data;
|
||||
|
||||
public class AppDb : PrefabDb, IPrefabDb,
|
||||
Prefab.Catalog.Data.IModuleDb,
|
||||
Prefab.Catalog.Data.IModuleDbReadOnly
|
||||
{
|
||||
public AppDb(DbContextOptions<AppDb> options, IHandlerContextAccessor accessor)
|
||||
: base(options, accessor)
|
||||
{
|
||||
}
|
||||
|
||||
protected AppDb(DbContextOptions options, IHandlerContextAccessor accessor)
|
||||
: base(options, accessor)
|
||||
{
|
||||
}
|
||||
|
||||
protected override void PrefabOnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
builder.ApplyConfigurationsFromAssembly(typeof(Prefab.Catalog.Data.IModuleDb).Assembly);
|
||||
}
|
||||
|
||||
protected override void PrefabOnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
// Additional write-context configuration can be applied here if needed.
|
||||
}
|
||||
|
||||
public DbSet<Category> Categories => Set<Category>();
|
||||
|
||||
public DbSet<Product> Products => Set<Product>();
|
||||
|
||||
public DbSet<OptionDefinition> OptionDefinitions => Set<OptionDefinition>();
|
||||
|
||||
public DbSet<OptionValue> OptionValues => Set<OptionValue>();
|
||||
|
||||
public DbSet<OptionTier> OptionTiers => Set<OptionTier>();
|
||||
|
||||
public DbSet<OptionRuleSet> OptionRuleSets => Set<OptionRuleSet>();
|
||||
|
||||
public DbSet<OptionRuleCondition> OptionRuleConditions => Set<OptionRuleCondition>();
|
||||
|
||||
public DbSet<VariantAxisValue> VariantAxisValues => Set<VariantAxisValue>();
|
||||
|
||||
public DbSet<AttributeDefinition> AttributeDefinitions => Set<AttributeDefinition>();
|
||||
|
||||
public DbSet<ProductAttributeValue> ProductAttributeValues => Set<ProductAttributeValue>();
|
||||
|
||||
public DbSet<ProductCategory> ProductCategories => Set<ProductCategory>();
|
||||
}
|
||||
20
Prefab.Catalog.Api/Data/AppDbReadOnly.cs
Normal file
20
Prefab.Catalog.Api/Data/AppDbReadOnly.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Prefab.Handler;
|
||||
|
||||
namespace Prefab.Catalog.Api.Data;
|
||||
|
||||
public class AppDbReadOnly(DbContextOptions<AppDbReadOnly> options, IHandlerContextAccessor accessor) : AppDb(options, accessor), Prefab.Data.IPrefabDbReadOnly,
|
||||
Prefab.Catalog.Data.IModuleDbReadOnly
|
||||
{
|
||||
protected override void PrefabOnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
base.PrefabOnConfiguring(optionsBuilder);
|
||||
optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
|
||||
}
|
||||
|
||||
public override int SaveChanges()
|
||||
=> throw new InvalidOperationException("This database context is read-only. Saving changes is not allowed.");
|
||||
|
||||
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
||||
=> throw new InvalidOperationException("This database context is read-only. Saving changes is not allowed.");
|
||||
}
|
||||
16
Prefab.Catalog.Api/Data/CatalogDbContextFactory.cs
Normal file
16
Prefab.Catalog.Api/Data/CatalogDbContextFactory.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Prefab.Catalog.Data;
|
||||
|
||||
namespace Prefab.Catalog.Api.Data;
|
||||
|
||||
internal sealed class CatalogDbContextFactory(
|
||||
IDbContextFactory<AppDb> writeFactory,
|
||||
IDbContextFactory<AppDbReadOnly> readFactory) : ICatalogDbContextFactory
|
||||
{
|
||||
public async ValueTask<IModuleDb> CreateWritableAsync(CancellationToken cancellationToken = default) =>
|
||||
await writeFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
public async ValueTask<IModuleDbReadOnly> CreateReadOnlyAsync(CancellationToken cancellationToken = default) =>
|
||||
await readFactory.CreateDbContextAsync(cancellationToken);
|
||||
}
|
||||
|
||||
30
Prefab.Catalog.Api/Dockerfile
Normal file
30
Prefab.Catalog.Api/Dockerfile
Normal file
@@ -0,0 +1,30 @@
|
||||
# See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
|
||||
|
||||
# This stage is used when running from VS in fast mode (Default for Debug configuration)
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
|
||||
USER $APP_UID
|
||||
WORKDIR /app
|
||||
EXPOSE 8080
|
||||
EXPOSE 8081
|
||||
|
||||
|
||||
# This stage is used to build the service project
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src
|
||||
COPY ["Prefab.Catalog.Api/Prefab.Catalog.Api.csproj", "Prefab.Catalog.Api/"]
|
||||
RUN dotnet restore "./Prefab.Catalog.Api/Prefab.Catalog.Api.csproj"
|
||||
COPY . .
|
||||
WORKDIR "/src/Prefab.Catalog.Api"
|
||||
RUN dotnet build "./Prefab.Catalog.Api.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
# This stage is used to publish the service project to be copied to the final stage
|
||||
FROM build AS publish
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
RUN dotnet publish "./Prefab.Catalog.Api.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
|
||||
|
||||
# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration)
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=publish /app/publish .
|
||||
ENTRYPOINT ["dotnet", "Prefab.Catalog.Api.dll"]
|
||||
50
Prefab.Catalog.Api/Module.cs
Normal file
50
Prefab.Catalog.Api/Module.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Prefab.Catalog.Data;
|
||||
using Prefab.Catalog.Api.Data;
|
||||
using Prefab.Data;
|
||||
using Prefab.Module;
|
||||
|
||||
namespace Prefab.Catalog.Api;
|
||||
|
||||
public class Module : IModule
|
||||
{
|
||||
public WebApplicationBuilder Build(WebApplicationBuilder builder)
|
||||
{
|
||||
var writeConnection = builder.Configuration.GetConnectionString("PrefabDb")
|
||||
?? throw new InvalidOperationException("Connection string 'PrefabDb' not found. Ensure the Aspire AppHost exposes the SQL resource.");
|
||||
var readConnection = builder.Configuration.GetConnectionString("PrefabDbReadOnly") ?? writeConnection;
|
||||
|
||||
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
||||
|
||||
builder.Services.AddDbContext<IPrefabDb, AppDb>(options =>
|
||||
options.UseSqlServer(writeConnection, sqlOptions => sqlOptions.EnableRetryOnFailure()));
|
||||
|
||||
builder.Services.AddDbContext<IPrefabDbReadOnly, AppDbReadOnly>(options =>
|
||||
options.UseSqlServer(readConnection, sqlOptions => sqlOptions.EnableRetryOnFailure()));
|
||||
|
||||
builder.Services.AddDbContextFactory<AppDb>(options =>
|
||||
options.UseSqlServer(writeConnection, sqlOptions => sqlOptions.EnableRetryOnFailure()), ServiceLifetime.Scoped);
|
||||
|
||||
builder.Services.AddDbContextFactory<AppDbReadOnly>(options =>
|
||||
options.UseSqlServer(readConnection, sqlOptions => sqlOptions.EnableRetryOnFailure()), ServiceLifetime.Scoped);
|
||||
|
||||
builder.Services.AddModuleDbInterfaces(typeof(AppDb));
|
||||
builder.Services.AddModuleDbInterfaces(typeof(AppDbReadOnly));
|
||||
|
||||
builder.Services.AddScoped<ICatalogDbContextFactory, CatalogDbContextFactory>();
|
||||
|
||||
//builder.Services.AddHostedService<DataSeeder>();
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
public WebApplication Configure(WebApplication app)
|
||||
{
|
||||
return app;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
23
Prefab.Catalog.Api/Prefab.Catalog.Api.csproj
Normal file
23
Prefab.Catalog.Api/Prefab.Catalog.Api.csproj
Normal file
@@ -0,0 +1,23 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>9d7c3534-10cb-48a3-bab8-4b35ca1dabcc</UserSecretsId>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0-rc.2.25502.107" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.0-rc.2.25502.107" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Prefab.Catalog\Prefab.Catalog.csproj" />
|
||||
<ProjectReference Include="..\Prefab.ServiceDefaults\Prefab.ServiceDefaults.csproj" />
|
||||
<ProjectReference Include="..\Prefab.Shared\Prefab.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
6
Prefab.Catalog.Api/Prefab.Catalog.Api.http
Normal file
6
Prefab.Catalog.Api/Prefab.Catalog.Api.http
Normal file
@@ -0,0 +1,6 @@
|
||||
@Prefab.Catalog.Api_HostAddress = http://localhost:5078
|
||||
|
||||
GET {{Prefab.Catalog.Api_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
33
Prefab.Catalog.Api/Program.cs
Normal file
33
Prefab.Catalog.Api/Program.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using Prefab.Module;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.AddServiceDefaults();
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.AddPrefab();
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UsePrefab();
|
||||
|
||||
app.MapDefaultEndpoints();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
31
Prefab.Catalog.Api/Properties/launchSettings.json
Normal file
31
Prefab.Catalog.Api/Properties/launchSettings.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true,
|
||||
"applicationUrl": "http://localhost:5078"
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true,
|
||||
"applicationUrl": "https://localhost:7164;http://localhost:5078"
|
||||
},
|
||||
"Container (Dockerfile)": {
|
||||
"commandName": "Docker",
|
||||
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_HTTPS_PORTS": "8081",
|
||||
"ASPNETCORE_HTTP_PORTS": "8080"
|
||||
},
|
||||
"publishAllPorts": true,
|
||||
"useSSL": true
|
||||
}
|
||||
},
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json"
|
||||
}
|
||||
76
Prefab.Catalog.Api/Workers/DataSeeder.cs
Normal file
76
Prefab.Catalog.Api/Workers/DataSeeder.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
using Prefab.Catalog.Api.Data;
|
||||
|
||||
namespace Prefab.Catalog.Api.Workers;
|
||||
|
||||
/// <summary>
|
||||
/// Background service for seeding data. Collects seed tasks from a channel and executes them concurrently.
|
||||
/// </summary>
|
||||
public class DataSeeder(IServiceProvider serviceProvider, IConfiguration configuration, ILogger<DataSeeder> logger) : BackgroundService
|
||||
{
|
||||
private readonly int _workerCount = configuration.GetValue("DataSeederWorkerCount", 4);
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
await WaitForDatabaseAsync(stoppingToken);
|
||||
|
||||
var tasks = new List<Task>();
|
||||
|
||||
for (var i = 0; i < _workerCount; i++)
|
||||
{
|
||||
tasks.Add(Task.Run(async () =>
|
||||
{
|
||||
await foreach (var seedTask in Prefab.Data.Seeder.Extensions.Channel.Reader.ReadAllAsync(stoppingToken))
|
||||
{
|
||||
try
|
||||
{
|
||||
await seedTask(serviceProvider, stoppingToken);
|
||||
logger.LogInformation("Seed task executed successfully.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error executing seed task.");
|
||||
// Optionally, add retry logic here.
|
||||
}
|
||||
}
|
||||
}, stoppingToken));
|
||||
}
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
private async Task WaitForDatabaseAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
var hasLoggedWait = false;
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = serviceProvider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDb>();
|
||||
|
||||
if (await db.Database.CanConnectAsync(stoppingToken))
|
||||
{
|
||||
if (hasLoggedWait)
|
||||
{
|
||||
logger.LogInformation("Database connectivity confirmed. Starting seed workers.");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogDebug(ex, "Database connectivity probe failed; retrying.");
|
||||
}
|
||||
|
||||
if (!hasLoggedWait)
|
||||
{
|
||||
logger.LogInformation("Waiting for database availability before processing seed tasks...");
|
||||
hasLoggedWait = true;
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
8
Prefab.Catalog.Api/appsettings.Development.json
Normal file
8
Prefab.Catalog.Api/appsettings.Development.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
9
Prefab.Catalog.Api/appsettings.json
Normal file
9
Prefab.Catalog.Api/appsettings.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
Reference in New Issue
Block a user