astral-api/Astral.ApiServer/HostedService/StartupService.cs

63 lines
2.1 KiB
C#
Raw Normal View History

2024-12-11 21:36:30 +01:00
// <copyright file="StartupService.cs" company="alveus.dev">
// Copyright (c) alveus.dev. All rights reserved. Licensed under the MIT License.
// </copyright>
using Astral.Core.Infrastructure;
using Astral.Services.Interfaces;
namespace Astral.ApiServer.HostedService;
/// <summary>
/// Processes to be executed at startup.
/// </summary>
public class StartupService : IHostedService
{
private readonly ILogger<StartupService> _logger;
private readonly IServiceScopeFactory _serviceScopeFactory;
/// <summary>
/// Initializes a new instance of the <see cref="StartupService" /> class.
/// </summary>
/// <param name="serviceScopeFactory">Instance of <see cref="IServiceScopeFactory" />.</param>
/// <param name="logger">Instance of <see cref="ILogger" />.</param>
public StartupService(
IServiceScopeFactory serviceScopeFactory,
ILogger<StartupService> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_logger = logger;
}
/// <inheritdoc />
public async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Running startup processes");
using var scope = _serviceScopeFactory.CreateScope();
// Database migrations.
var dbMigrator = scope.ServiceProvider.GetRequiredService<IDatabaseMigrator>();
await dbMigrator.MigrateDatabaseAsync(AppDomain.CurrentDomain.BaseDirectory + "Migrations");
// DAL setup.
var dalSetup = scope.ServiceProvider.GetService<IDataAccessLayerSetup>();
if (dalSetup is not null)
{
await dalSetup.Setup();
}
// Email address domain blacklist update.
var emDomainBlacklist = scope.ServiceProvider.GetRequiredService<IEmailDomainBlacklistService>();
await emDomainBlacklist.UpdateBlacklist();
// Initial user setup.
var initialUserSetup = scope.ServiceProvider.GetRequiredService<IInitialUserService>();
await initialUserSetup.CreateFirstUserIfRequiredAsync();
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}