galaeth-draft/Galaeth.ApiServer/HostedServices/StartupService.cs
2024-11-17 09:31:01 +00:00

59 lines
2 KiB
C#

using Galaeth.Core.Infrastructure;
using Galaeth.Services.Interfaces;
namespace Galaeth.ApiServer.HostedServices;
/// <summary>
/// Processes to be executed at startup.
/// </summary>
public class StartupService : IHostedService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ILogger<StartupService> _logger;
/// <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;
}
}