Style: C# 12 Primary constructor

This commit is contained in:
Kamigen
2024-03-30 20:59:17 -04:00
parent 786c65410d
commit 8f58311283
50 changed files with 267 additions and 449 deletions

View File

@@ -7,10 +7,10 @@ using Microsoft.EntityFrameworkCore;
namespace Hutopy.Infrastructure.Data;
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IApplicationDbContext
public class ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options)
: IdentityDbContext<ApplicationUser>(options), IApplicationDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
public DbSet<TodoList> TodoLists => Set<TodoList>();
public DbSet<TodoItem> TodoItems => Set<TodoItem>();

View File

@@ -1,5 +1,4 @@
using System.Runtime.InteropServices;
using Hutopy.Domain.Constants;
using Hutopy.Domain.Constants;
using Hutopy.Domain.Entities;
using Hutopy.Infrastructure.Identity;
using Microsoft.AspNetCore.Builder;
@@ -10,44 +9,35 @@ using Microsoft.Extensions.Logging;
namespace Hutopy.Infrastructure.Data;
public static class InitialiserExtensions
public static class InitializerExtensions
{
public static async Task InitialiseDatabaseAsync(this WebApplication app)
{
using var scope = app.Services.CreateScope();
var initialiser = scope.ServiceProvider.GetRequiredService<ApplicationDbContextInitialiser>();
var initializer = scope.ServiceProvider.GetRequiredService<ApplicationDbContextInitializer>();
await initialiser.InitialiseAsync();
await initializer.InitialiseAsync();
await initialiser.SeedAsync();
await initializer.SeedAsync();
}
}
public class ApplicationDbContextInitialiser
public class ApplicationDbContextInitializer(
ILogger<ApplicationDbContextInitializer> logger,
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
{
private readonly ILogger<ApplicationDbContextInitialiser> _logger;
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public ApplicationDbContextInitialiser(ILogger<ApplicationDbContextInitialiser> logger, ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
_logger = logger;
_context = context;
_userManager = userManager;
_roleManager = roleManager;
}
public async Task InitialiseAsync()
{
try
{
await _context.Database.MigrateAsync();
await context.Database.MigrateAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while initialising the database.");
logger.LogError(ex, "An error occurred while initialising the database.");
throw;
}
}
@@ -60,38 +50,38 @@ public class ApplicationDbContextInitialiser
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while seeding the database.");
logger.LogError(ex, "An error occurred while seeding the database.");
throw;
}
}
public async Task TrySeedAsync()
private async Task TrySeedAsync()
{
// Default roles
var administratorRole = new IdentityRole(Roles.Administrator);
if (_roleManager.Roles.All(r => r.Name != administratorRole.Name))
if (roleManager.Roles.All(r => r.Name != administratorRole.Name))
{
await _roleManager.CreateAsync(administratorRole);
await roleManager.CreateAsync(administratorRole);
}
// Default users
var administrator = new ApplicationUser { UserName = "administrator@localhost", Email = "administrator@localhost" };
if (_userManager.Users.All(u => u.UserName != administrator.UserName))
if (userManager.Users.All(u => u.UserName != administrator.UserName))
{
await _userManager.CreateAsync(administrator, "Administrator1!");
await userManager.CreateAsync(administrator, "Administrator1!");
if (!string.IsNullOrWhiteSpace(administratorRole.Name))
{
await _userManager.AddToRolesAsync(administrator, new [] { administratorRole.Name });
await userManager.AddToRolesAsync(administrator, new [] { administratorRole.Name });
}
}
// Default data
// Seed, if necessary
if (!_context.TodoLists.Any())
if (!context.TodoLists.Any())
{
_context.TodoLists.Add(new TodoList
context.TodoLists.Add(new TodoList
{
Title = "Todo List",
Items =
@@ -103,7 +93,7 @@ public class ApplicationDbContextInitialiser
}
});
await _context.SaveChangesAsync();
await context.SaveChangesAsync();
}
}
}

View File

@@ -6,19 +6,10 @@ using Microsoft.EntityFrameworkCore.Diagnostics;
namespace Hutopy.Infrastructure.Data.Interceptors;
public class AuditableEntityInterceptor : SaveChangesInterceptor
public class AuditableEntityInterceptor(
IUser user,
TimeProvider dateTime) : SaveChangesInterceptor
{
private readonly IUser _user;
private readonly TimeProvider _dateTime;
public AuditableEntityInterceptor(
IUser user,
TimeProvider dateTime)
{
_user = user;
_dateTime = dateTime;
}
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
{
UpdateEntities(eventData.Context);
@@ -41,13 +32,13 @@ public class AuditableEntityInterceptor : SaveChangesInterceptor
{
if (entry.State is EntityState.Added or EntityState.Modified || entry.HasChangedOwnedEntities())
{
var utcNow = _dateTime.GetUtcNow();
var utcNow = dateTime.GetUtcNow();
if (entry.State == EntityState.Added)
{
entry.Entity.CreatedBy = _user.Id;
entry.Entity.CreatedBy = user.Id;
entry.Entity.Created = utcNow;
}
entry.Entity.LastModifiedBy = _user.Id;
entry.Entity.LastModifiedBy = user.Id;
entry.Entity.LastModified = utcNow;
}
}

View File

@@ -5,15 +5,10 @@ using Microsoft.EntityFrameworkCore.Diagnostics;
namespace Hutopy.Infrastructure.Data.Interceptors;
public class DispatchDomainEventsInterceptor : SaveChangesInterceptor
public class DispatchDomainEventsInterceptor(
IPublisher mediator)
: SaveChangesInterceptor
{
private readonly IMediator _mediator;
public DispatchDomainEventsInterceptor(IMediator mediator)
{
_mediator = mediator;
}
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
{
DispatchDomainEvents(eventData.Context).GetAwaiter().GetResult();
@@ -45,6 +40,6 @@ public class DispatchDomainEventsInterceptor : SaveChangesInterceptor
entities.ToList().ForEach(e => e.ClearDomainEvents());
foreach (var domainEvent in domainEvents)
await _mediator.Publish(domainEvent);
await mediator.Publish(domainEvent);
}
}