conocimientogenerador-crudtemplates/2793 B
ApplicationDbContext.cs.template
Fichero que /hv:generador-crud usa o materializa en el proyecto. Se muestra tal cual está en el plugin.
// ============================================================================
// TEMPLATE: ApplicationDbContext.cs - DbContext del proyecto (una vez por proyecto)
// Skill: generador-crud (ADR-031)
// ============================================================================
// USO: Reemplazar {{Namespace}} y {{DbSets}} (un DbSet por entidad generada). Se genera si no existe; si ya
// existe, se ANADE el DbSet de la entidad nueva y no se toca nada mas.
// Destino: src/Infrastructure/Persistence/ApplicationDbContext.cs
// Implementa IUnitOfWork (los handlers guardan a traves del puerto, no del DbContext), aplica las
// IEntityTypeConfiguration del ensamblado y registra los interceptores de auditoria y borrado logico.
// ============================================================================
using Microsoft.EntityFrameworkCore;
using {{Namespace}}.Application.Common.Interfaces;
using {{Namespace}}.Domain.Entities;
using {{Namespace}}.Infrastructure.Persistence.Interceptors;
namespace {{Namespace}}.Infrastructure.Persistence;
public class ApplicationDbContext : DbContext, IUnitOfWork
{
private readonly AuditableInterceptor _auditable;
private readonly SoftDeleteInterceptor _softDelete;
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options,
AuditableInterceptor auditable,
SoftDeleteInterceptor softDelete)
: base(options)
{
_auditable = auditable;
_softDelete = softDelete;
}
{{DbSets}}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.AddInterceptors(_auditable, _softDelete);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly);
base.OnModelCreating(modelBuilder);
}
}
// ═══════════════════════════════════════════════════════════════════════════
// REGISTRO EN DI (Infrastructure/DependencyInjection.cs)
// ═══════════════════════════════════════════════════════════════════════════
/*
services.AddSingleton(TimeProvider.System);
services.AddScoped<ICurrentUserService, HttpContextUserService>();
services.AddScoped<AuditableInterceptor>();
services.AddScoped<SoftDeleteInterceptor>();
services.AddDbContext<ApplicationDbContext>(o => o.UseSqlServer(connectionString));
services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<ApplicationDbContext>());
*/