From fee14afb89c15e8cca0937c814461c64d8fdb8a0 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 14 Aug 2026 09:03:30 -0700 Subject: [PATCH] Replaces reflection-based repository instantiation with unit of work property accessors --- .../architecture-decision-record-0001.md | 2 +- .../Common/DataAccess/UoW/IUnitOfWork.cs | 95 +++++- .../GetPermissionsQueryHandler.cs | 6 +- .../Commands/AddRole/AddRoleCommandHandler.cs | 6 +- .../DeleteRole/DeleteRoleCommandHandler.cs | 5 +- .../UpdateRole/UpdateRoleCommandHandler.cs | 6 +- .../GetRolePermissionsQueryHandler.cs | 2 +- .../Queries/GetRoles/GetRolesQueryHandler.cs | 2 +- .../SetupApplicationCommandHandler.cs | 5 +- .../CheckInitializationQueryHandler.cs | 3 +- .../AddLibrary/AddLibraryCommandHandler.cs | 6 +- .../CancelLibrariesScanCommandHandler.cs | 6 +- .../CancelLibraryScanCommandHandler.cs | 6 +- .../DeleteLibraryCommandHandler.cs | 5 +- .../ScanLibrariesCommandHandler.cs | 9 +- .../ScanLibrary/ScanLibraryCommandHandler.cs | 9 +- .../UpdateLibraryCommandHandler.cs | 7 +- .../Events/LibrarySavedDomainEventHandler.cs | 3 +- .../LibraryScanCancelledDomainEventHandler.cs | 8 +- .../LibraryScanFailedDomainEventHandler.cs | 9 +- .../LibraryScanFinishedDomainEventHandler.cs | 6 +- .../LibraryScanQueuedDomainEventHandler.cs | 4 +- .../LibraryScanStartedDomainEventHandler.cs | 4 +- .../GetEnabledLibrariesQueryHandler.cs | 3 +- .../GetLibraries/GetLibrariesQueryHandler.cs | 3 +- .../GetLibrary/GetLibraryQueryHandler.cs | 3 +- .../GetLibraryScanProgressQueryHandler.cs | 3 +- .../GetRunningLibraryScansQueryHandler.cs | 3 +- .../Commands/AddBook/AddBookCommandHandler.cs | 3 +- .../Queries/GetBooks/GetBooksQueryHandler.cs | 4 +- ...rLibraryMetadataProvidersCommandHandler.cs | 5 +- ...ryMetadataProviderEnabledCommandHandler.cs | 7 +- .../UpdatePluginSettingsCommandHandler.cs | 3 +- ...GetLibraryMetadataProvidersQueryHandler.cs | 6 +- .../GetPluginSettingsQueryHandler.cs | 3 +- .../GetPlugins/GetPluginsQueryHandler.cs | 7 +- .../ChangePasswordCommandHandler.cs | 5 +- .../RecoverPasswordCommandHandler.cs | 5 +- .../RegisterUserCommandHandler.cs | 5 +- .../Queries/GetUsers/GetUsersQueryHandler.cs | 6 +- .../LoginUser/LoginUserQueryHandler.cs | 5 +- ...ateUserRoleAndPermissionsCommandHandler.cs | 19 +- .../GetUserPermissionsQueryHandler.cs | 6 +- .../GetUserRole/GetUserRoleQueryHandler.cs | 6 +- .../DataAccessLayerServices.cs | 26 -- .../Common/Factory/IRepositoryFactory.cs | 15 - .../Common/Factory/RepositoryDictionary.cs | 64 ---- .../Common/Factory/RepositoryFactory.cs | 34 --- .../Core/Seed/DataSeedService.cs | 28 +- src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs | 280 +++++++++++++----- .../Authorization/AuthorizationService.cs | 14 +- .../Policies/Over18/Over18Policy.cs | 6 +- .../Jobs/Common/MediaLibraryScanDiffJob.cs | 4 +- .../Jobs/Common/MediaLibraryScanHashJob.cs | 8 +- .../MediaLibraryScanMetadataEnrichmentJob.cs | 15 +- .../Common/MediaLibraryScanResultsSaveJob.cs | 14 +- .../Books/BooksFileSystemDiscoveryJob.cs | 15 +- .../Core/Plugins/PluginDetectionSyncJob.cs | 3 +- .../Core/Plugins/PluginSettingsStore.cs | 3 +- .../GetPermissionsQueryHandlerTests.cs | 2 +- .../AddRole/AddRoleCommandHandlerTests.cs | 2 +- .../DeleteRoleCommandHandlerTests.cs | 2 +- .../UpdateRoleCommandHandlerTests.cs | 2 +- .../GetRolePermissionsQueryHandlerTests.cs | 2 +- .../GetRoles/GetRolesQueryHandlerTests.cs | 2 +- .../SetupApplicationCommandHandlerTests.cs | 2 +- .../CheckInitializationQueryHandlerTests.cs | 2 +- .../AddBook/AddBookCommandHandlerTests.cs | 2 +- ...aryMetadataProvidersCommandHandlerTests.cs | 2 +- ...adataProviderEnabledCommandHandlerTests.cs | 2 +- ...UpdatePluginSettingsCommandHandlerTests.cs | 2 +- .../GetPlugins/GetPluginsQueryHandlerTests.cs | 2 +- .../ChangePasswordCommandHandlerTests.cs | 2 +- .../RecoverPasswordCommandHandlerTests.cs | 2 +- .../RegisterUserCommandHandlerTests.cs | 2 +- .../GetUsers/GetUsersQueryHandlerTests.cs | 2 +- .../LoginUser/LoginUserQueryHandlerTests.cs | 2 +- ...erRoleAndPermissionsCommandHandlerTests.cs | 6 +- .../GetUserPermissionsQueryHandlerTests.cs | 2 +- .../GetUserRoleQueryHandlerTests.cs | 2 +- .../DataAccessLayerServicesTests.cs | 14 +- .../Fixtures/IUnregisteredRepository.cs | 6 - .../Factory/RepositoryDictionaryTests.cs | 107 ------- .../Common/Factory/RepositoryFactoryTests.cs | 58 ---- .../Core/Seed/DataSeedServiceTests.cs | 54 ++-- .../Core/UoW/UnitOfWorkTests.cs | 136 ++++----- .../AuthorizationServiceTests.cs | 2 +- 87 files changed, 541 insertions(+), 735 deletions(-) delete mode 100644 src/Lumina.DataAccess/Core/Repositories/Common/Factory/IRepositoryFactory.cs delete mode 100644 src/Lumina.DataAccess/Core/Repositories/Common/Factory/RepositoryDictionary.cs delete mode 100644 src/Lumina.DataAccess/Core/Repositories/Common/Factory/RepositoryFactory.cs delete mode 100644 tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/Fixtures/IUnregisteredRepository.cs delete mode 100644 tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryDictionaryTests.cs delete mode 100644 tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryFactoryTests.cs diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md index 7a4a7395..d4f5ea08 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md @@ -31,7 +31,7 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD { await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService(); - ILibraryRepository libraryRepository = unitOfWork.GetRepository(); + ILibraryRepository libraryRepository = unitOfWork.LibraryRepository; // execution logic } } diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index 7de99390..9d2b4442 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -1,4 +1,9 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.Authorization; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Users; using System.Threading; using System.Threading.Tasks; #endregion @@ -11,11 +16,69 @@ namespace Lumina.Application.Common.DataAccess.UoW; public interface IUnitOfWork { /// - /// Exposes a repository of type to the Business Layer. + /// Gets the permission repository. /// - /// The type of the exposed repository. - /// A repository of type . - TRepository GetRepository(); + IPermissionRepository PermissionRepository { get; } + + /// + /// Gets the role permission repository. + /// + IRolePermissionRepository RolePermissionRepository { get; } + + /// + /// Gets the role repository. + /// + IRoleRepository RoleRepository { get; } + + /// + /// Gets the role user repository. + /// + IUserRoleRepository UserRoleRepository { get; } + + /// + /// Gets the book repository. + /// + IBookRepository BookRepository { get; } + + /// + /// Gets the directory scan fingerprint repository. + /// + IDirectoryScanFingerprintRepository DirectoryScanFingerprintRepository { get; } + + /// + /// Gets the library repository. + /// + ILibraryRepository LibraryRepository { get; } + + /// + /// Gets the library scan repository. + /// + ILibraryScanRepository LibraryScanRepository { get; } + + /// + /// Gets the library scan snapshot repository. + /// + ILibraryScanSnapshotRepository LibraryScanSnapshotRepository { get; } + + /// + /// Gets the library scan staging results repository. + /// + ILibraryScanStagingResultsRepository LibraryScanStagingResultsRepository { get; } + + /// + /// Gets the library metadata provider configuration repository. + /// + ILibraryMetadataProviderConfigurationRepository LibraryMetadataProviderConfigurationRepository { get; } + + /// + /// Gets the plugin repository. + /// + IPluginRepository PluginRepository { get; } + + /// + /// Gets the user repository. + /// + IUserRepository UserRepository { get; } /// /// Saves all changes made to the database. @@ -24,12 +87,24 @@ public interface IUnitOfWork Task SaveChangesAsync(CancellationToken cancellationToken); /// - /// Opens a transaction. + /// Begins a new database transaction. /// - void OpenTransaction(); + /// Cancellation token that can be used to stop the execution. + /// A task representing the asynchronous operation. + Task BeginTransactionAsync(CancellationToken cancellationToken); /// - /// Commits a transaction. + /// Commits the current transaction. /// - void CommitTransaction(); -} \ No newline at end of file + /// Cancellation token that can be used to stop the execution. + /// A task representing the asynchronous operation. + Task CommitTransactionAsync(CancellationToken cancellationToken); + + + /// + /// Rolls back the current transaction. + /// + /// Cancellation token that can be used to stop the execution. + /// A task representing the asynchronous operation. + Task RollbackTransactionAsync(CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs index da4ef78e..406692dd 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs @@ -22,8 +22,8 @@ namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPer public class GetPermissionsQueryHandler : IQueryHandler>> { private readonly ICurrentUserService _currentUserService; + private readonly IUnitOfWork _unitOfWork; private readonly IAuthorizationService _authorizationService; - private readonly IPermissionRepository _permissionRepository; /// /// Initializes a new instance of the class. @@ -35,7 +35,7 @@ public class GetPermissionsQueryHandler : IQueryHandler(); + _unitOfWork = unitOfWork; } /// @@ -52,7 +52,7 @@ public class GetPermissionsQueryHandler : IQueryHandler> getPermissionsResult = await _permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); return getPermissionsResult.Match(value => Result.From(value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs index f86006d8..a766699f 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs @@ -62,8 +62,6 @@ public class AddRoleCommandHandler : ICommandHandler(); - // create the new role, with its permissions RoleEntity newRole = new() { @@ -77,12 +75,12 @@ public class AddRoleCommandHandler : ICommandHandler insertRoleResult = await roleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false); + Result insertRoleResult = await _unitOfWork.RoleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false); if (insertRoleResult.IsFailure) return insertRoleResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // retrieve the newly saved authorization role from the persistence medium and return it - Result getRoleResult = await roleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false); + Result getRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false); if (getRoleResult.IsFailure) return getRoleResult.Errors; if (getRoleResult.Value is null) diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs index fb4ed8fe..1dcfffa5 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs @@ -62,8 +62,7 @@ public class DeleteRoleCommandHandler : ICommandHandler(); - Result getExistingRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); + Result getExistingRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); if (getExistingRoleResult.IsFailure) return getExistingRoleResult.Errors; else if (getExistingRoleResult.Value is null) @@ -71,7 +70,7 @@ public class DeleteRoleCommandHandler : ICommandHandler deleteRoleResult = await roleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); + Result deleteRoleResult = await _unitOfWork.RoleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); if (deleteRoleResult.IsFailure) return deleteRoleResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs index 3dcb67c2..bde17eb5 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs @@ -62,8 +62,6 @@ public class UpdateRoleCommandHandler : ICommandHandler(); - // update the role and its permissions RoleEntity newRole = new() { @@ -78,12 +76,12 @@ public class UpdateRoleCommandHandler : ICommandHandler updateRoleResult = await roleRepository.UpdateAsync(newRole, cancellationToken).ConfigureAwait(false); + Result updateRoleResult = await _unitOfWork.RoleRepository.UpdateAsync(newRole, cancellationToken).ConfigureAwait(false); if (updateRoleResult.IsFailure) return updateRoleResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // retrieve the updated authorization role from the persistence medium and return it - Result getRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); + Result getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); if (getRoleResult.IsFailure) return getRoleResult.Errors; if (getRoleResult.Value is null) diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs index b3455ca1..cdb9f253 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs @@ -38,7 +38,7 @@ public class GetRolePermissionsQueryHandler : IQueryHandler(); + _roleRepository = unitOfWork.RoleRepository; _validator = validator; } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs index 909a68f1..c194da0d 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs @@ -35,7 +35,7 @@ public class GetRolesQueryHandler : IQueryHandler(); + _roleRepository = unitOfWork.RoleRepository; } /// diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs index a2179d80..fdc1df53 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -80,8 +80,7 @@ public class SetupApplicationCommandHandler : ICommandHandler(); - Result> selectUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); if (selectUsersResult.IsFailure) return selectUsersResult.Errors; else if (selectUsersResult.Value.Any()) @@ -112,7 +111,7 @@ public class SetupApplicationCommandHandler : ICommandHandler insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); + Result insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); if (insertUserResult.IsFailure) return insertUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs index 56db7aa7..8f2dba4c 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs @@ -38,9 +38,8 @@ public class CheckInitializationQueryHandler : IQueryHandler public async Task HandleAsync(CheckInitializationQuery query, CancellationToken cancellationToken) { - IUserRepository userRepository = _unitOfWork.GetRepository(); // if the repository reports an error, or there are no users, the application has not been initialized - Result> selectUsersResult = await userRepository.GetAllAsync(cancellationToken); + Result> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken); if (!selectUsersResult.IsFailure) return new InitializationResponse(selectUsersResult.Value.Any()); return new InitializationResponse(false); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 9c105181..e3ae610c 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -116,18 +116,16 @@ public class AddLibraryCommandHandler : ICommandHandler(); // convert the domain library entity to a repository library entity LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity(); // insert the repository entity and save changes - Result insertLibraryResult = await libraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); + Result insertLibraryResult = await _unitOfWork.LibraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); if (insertLibraryResult.IsFailure) return insertLibraryResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // retrieve the newly saved media library from the persistence medium and return it - Result getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + Result getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); if (getCreatedLibraryResult.IsFailure) return getCreatedLibraryResult.Errors; if (getCreatedLibraryResult.Value is null) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs index 530cf153..5260d660 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs @@ -56,10 +56,8 @@ public class CancelLibrariesScanCommandHandler : ICommandHandlerAn representing either a successful operation, or an error. public async Task> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken) { - ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); - // get the running library scans of the current user from the repository - Result> getRunningLibraryScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); + Result> getRunningLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); if (getRunningLibraryScansResult.IsFailure) return getRunningLibraryScansResult.Errors; @@ -88,7 +86,7 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) return updateLibraryScanResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs index db7cc2f3..e6220e5e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs @@ -65,10 +65,8 @@ public class CancelLibraryScanCommandHandler : ICommandHandler 0) return validationResult; - ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); - // get the library scan from the repository - Result getLibraryScansResult = await libraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false); + Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsFailure) return getLibraryScansResult.Errors; if (getLibraryScansResult.Value is null) @@ -90,7 +88,7 @@ public class CancelLibraryScanCommandHandler : ICommandHandler updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) return updateLibraryScanResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs index 40eeaae0..2ab5d12f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs @@ -66,8 +66,7 @@ public class DeleteLibraryCommandHandler : ICommandHandler(); - Result getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) @@ -93,7 +92,7 @@ public class DeleteLibraryCommandHandler : ICommandHandler deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + Result deletePersistenceLibraryResult = await _unitOfWork.LibraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (deletePersistenceLibraryResult.IsFailure) return deletePersistenceLibraryResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs index 616e50ee..9d60f10d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs @@ -59,11 +59,8 @@ public class ScanLibrariesCommandHandler : ICommandHandlerAn representing either a successful operation, or an error. public async Task>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken) { - ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); - ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); - // get all media libraries that are enabled and unlocked from the persistence medium - Result> getLibrariesResult = await libraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false); + Result> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false); if (getLibrariesResult.IsFailure) return getLibrariesResult.Errors; @@ -85,7 +82,7 @@ public class ScanLibrariesCommandHandler : ICommandHandler> pastLibraryScansResult = - await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(domainLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + await _unitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(domainLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); if (pastLibraryScansResult.IsFailure) return pastLibraryScansResult.Errors; @@ -111,7 +108,7 @@ public class ScanLibrariesCommandHandler : ICommandHandler insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + Result insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (insertLibraryScanResult.IsFailure) return insertLibraryScanResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs index d22135bf..73f6d713 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs @@ -71,11 +71,8 @@ public class ScanLibraryCommandHandler : ICommandHandler 0) return validationResult; - ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); - ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); - // get the media library from the persistence medium - Result getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; @@ -100,7 +97,7 @@ public class ScanLibraryCommandHandler : ICommandHandler> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + Result> pastLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (pastLibraryScansResult.IsFailure) return pastLibraryScansResult.Errors; @@ -124,7 +121,7 @@ public class ScanLibraryCommandHandler : ICommandHandler insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + Result insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (insertLibraryScanResult.IsFailure) return insertLibraryScanResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index 70432b7f..bab2e592 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -97,8 +97,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler(); - Result getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) @@ -131,13 +130,13 @@ public class UpdateLibraryCommandHandler : ICommandHandler updateLibraryResult = await libraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); + Result updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); if (updateLibraryResult.IsFailure) return updateLibraryResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // retrieve the updated media library from the persistence medium and return it - Result getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + Result getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); if (getCreatedLibraryResult.IsFailure) return getCreatedLibraryResult.Errors; if (getCreatedLibraryResult.Value is null) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs index 638d1778..d1a8f916 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs @@ -66,8 +66,7 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler(); - Result updateLibraryResult = await libraryRepository.UpdateAsync(domainEvent.Library.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + Result updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(domainEvent.Library.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryResult.IsFailure) throw new EventualConsistencyException(updateLibraryResult.FirstError, updateLibraryResult.Errors); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs index fdbd0be7..64e841e5 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs @@ -28,7 +28,6 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler @@ -47,7 +46,6 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler(); _unitOfWork = unitOfWork; } @@ -59,7 +57,7 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler getLibraryScansResult = await _libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsFailure) throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); if (getLibraryScansResult.Value is null) @@ -76,11 +74,11 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler(); + MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, UserId.Create(getLibraryScansResult.Value.UserId)); _mediaLibrariesScanCancellationTracker.RemoveScan(compositeId); _mediaLibrariesScanProgressTracker.RemoveScanProgress(compositeId); - Result clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + Result clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); if (clearStagingResult.IsFailure) throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors); } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs index e4b6d3d3..1bede197 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs @@ -54,11 +54,8 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken) { - ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); - ILibraryScanStagingResultsRepository stagingResultsRepository = _unitOfWork.GetRepository(); - // get the library scan from the repository - Result getLibraryScansResult = await libraryScanRepository.GetByIdAsync( + Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync( domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsFailure) throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); @@ -77,7 +74,7 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandler updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); @@ -87,7 +84,7 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandler clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); + Result clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); if (clearStagingResult.IsFailure) throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs index c5f7a482..c541f390 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs @@ -54,10 +54,8 @@ public class LibraryScanFinishedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken) { - ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); - // get the library scan from the repository - Result getLibraryScansResult = await libraryScanRepository.GetByIdAsync( + Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync( domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsFailure) throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); @@ -75,7 +73,7 @@ public class LibraryScanFinishedDomainEventHandler : IDomainEventHandler updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs index 2f18693e..4921de9d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs @@ -48,10 +48,8 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken) { - ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); - // get the library scan that was queued, from the repository - Result getLibraryScanResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + Result getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); if (getLibraryScanResult.IsFailure || getLibraryScanResult.Value is null) throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs index d66ffe68..ac2140c8 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs @@ -35,10 +35,8 @@ public class LibraryScanStartedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken) { - ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); - // update the status of the library scan in the repository - Result updateLibraryScanResult = await libraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs index f6ed371f..1934d7b1 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandler.cs @@ -52,8 +52,7 @@ public class GetEnabledLibrariesQueryHandler : IQueryHandler> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken) { // get the enabled libraries from the repository - ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); - Result> getEnabledLibrariesResult = await libraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false); + Result> getEnabledLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false); if (getEnabledLibrariesResult.IsFailure) return getEnabledLibrariesResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs index 0cba2396..98b8c06e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs @@ -52,8 +52,7 @@ public class GetLibrariesQueryHandler : IQueryHandler> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken) { // get the libraries from the repository - ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); - Result> getLibrariesResult = await libraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); if (getLibrariesResult.IsFailure) return getLibrariesResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs index 46766776..edd9f71d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs @@ -63,8 +63,7 @@ public class GetLibraryQueryHandler : IQueryHandler(); - Result getLibraryResult = await libraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs index 3630ca73..fabb5c64 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs @@ -70,8 +70,7 @@ public class GetLibraryScanProgressQueryHandler : IQueryHandler(); - Result getLibraryResult = await libraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs index ac3bae15..5cfb572a 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs @@ -59,8 +59,7 @@ public class GetRunningLibraryScansQueryHandler : IQueryHandler>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken) { // get the ongoing library scans from the repository - ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); - Result> getRunningScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); + Result> getRunningScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); if (getRunningScansResult.IsFailure) return getRunningScansResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs index a7498103..82be9a0d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs @@ -171,9 +171,8 @@ public class AddBookCommandHandler : ICommandHandler(); BookEntity persistenceBook = createBookResult.Value.ToRepositoryEntity(); - Result insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false); + Result insertBookResult = await _unitOfWork.BookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false); if (insertBookResult.IsFailure) return insertBookResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs index 1fecb892..5cc1b35e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs @@ -39,10 +39,8 @@ public class GetBooksQueryHandler : IQueryHandler public async Task>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken) { - // get a books repository - IBookRepository bookRepository = _unitOfWork.GetRepository(); // get all books of the media library from the book repository - Result> getBooksResult = await bookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); + Result> getBooksResult = await _unitOfWork.BookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); return getBooksResult.Match(result => Result.From(getBooksResult.Value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs index 5ef6f702..b04e7a35 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs @@ -47,8 +47,7 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler 0) return validationResult; - ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository(); - Result> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); + Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; @@ -59,7 +58,7 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler upsertResult = await configurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + Result upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); if (upsertResult.IsFailure) return upsertResult.Errors; } diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs index 8f52da04..d3d8eee5 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs @@ -47,8 +47,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler 0) return validationResult; - ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository(); - Result getConfigurationResult = await configurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); + Result getConfigurationResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); if (getConfigurationResult.IsFailure) return getConfigurationResult.Errors; @@ -61,7 +60,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); + Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; @@ -78,7 +77,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler upsertResult = await configurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + Result upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); if (upsertResult.IsFailure) return upsertResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs index a2f23f25..780748dc 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs @@ -45,9 +45,8 @@ public class UpdatePluginSettingsCommandHandler : ICommandHandler 0) return validationResult; - IPluginRepository pluginRepository = _unitOfWork.GetRepository(); string? settingsJson = command.Settings is not null ? JsonSerializer.Serialize(command.Settings) : null; - Result updateResult = await pluginRepository.UpdateSettingsAsync(command.PluginId, settingsJson, cancellationToken).ConfigureAwait(false); + Result updateResult = await _unitOfWork.PluginRepository.UpdateSettingsAsync(command.PluginId, settingsJson, cancellationToken).ConfigureAwait(false); if (updateResult.IsFailure) return updateResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs index c8cee410..6ed087fe 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs @@ -41,14 +41,12 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler public async Task>> HandleAsync(GetLibraryMetadataProvidersQuery query, CancellationToken cancellationToken) { - ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository(); - Result> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); + Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; // build a plugin name lookup from the detected plugins - IPluginRepository pluginRepository = _unitOfWork.GetRepository(); - Result> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); if (getPluginsResult.IsFailure) return getPluginsResult.Errors; Dictionary pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs index 91941e01..5e26b31d 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs @@ -46,8 +46,7 @@ public class GetPluginSettingsQueryHandler : IQueryHandler public async Task> HandleAsync(GetPluginSettingsQuery query, CancellationToken cancellationToken) { - IPluginRepository pluginRepository = _unitOfWork.GetRepository(); - Result getPluginResult = await pluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false); + Result getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false); if (getPluginResult.IsFailure) return getPluginResult.Errors; PluginEntity? pluginEntity = getPluginResult.Value; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs index 4bc6e340..df20f182 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs @@ -40,10 +40,7 @@ public class GetPluginsQueryHandler : IQueryHandler public async Task>> HandleAsync(GetPluginsQuery query, CancellationToken cancellationToken) { - IPluginRepository pluginRepository = _unitOfWork.GetRepository(); - Result> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - return getPluginsResult.Match( - plugins => Result.From>(plugins.Select(plugin => plugin.ToResponse()).ToList()), - errors => errors); + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + return getPluginsResult.Match(plugins => Result.From>([.. plugins.Select(plugin => plugin.ToResponse())]), errors => errors); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs index 0304d7cf..1f5d127a 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs @@ -55,8 +55,7 @@ public class ChangePasswordCommandHandler : ICommandHandler 0) return validationResult; - IUserRepository userRepository = _unitOfWork.GetRepository(); - Result getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) @@ -69,7 +68,7 @@ public class ChangePasswordCommandHandler : ICommandHandler updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); + Result updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); if (updateUserResult.IsFailure) return updateUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs index 98c1626c..e97e1704 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs @@ -65,8 +65,7 @@ public class RecoverPasswordCommandHandler : ICommandHandler(); - Result getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) @@ -86,7 +85,7 @@ public class RecoverPasswordCommandHandler : ICommandHandler updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); + Result updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); if (updateUserResult.IsFailure) return updateUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs index be45419c..7777826d 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs @@ -74,8 +74,7 @@ public class RegisterUserCommandHandler : ICommandHandler(); - Result getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is not null) @@ -105,7 +104,7 @@ public class RegisterUserCommandHandler : ICommandHandler insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); + Result insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); if (insertUserResult.IsFailure) return insertUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs index 5cede5a5..f5ab1e75 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs @@ -22,9 +22,9 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUser /// public class GetUsersQueryHandler : IQueryHandler>> { + private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; - private readonly IUserRepository _userRepository; /// /// Initializes a new instance of the class. @@ -36,7 +36,7 @@ public class GetUsersQueryHandler : IQueryHandler(); + _unitOfWork = unitOfWork; } /// @@ -53,7 +53,7 @@ public class GetUsersQueryHandler : IQueryHandler> getRolesResult = await _userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); return getRolesResult.Match(value => Result.From(value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs index cdabc541..919a348d 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs @@ -74,8 +74,7 @@ public class LoginUserQueryHandler : IQueryHandler(); - Result getUserResult = await userRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) @@ -91,7 +90,7 @@ public class LoginUserQueryHandler : IQueryHandler(); - IRoleRepository roleRepository = _unitOfWork.GetRepository(); - IPermissionRepository permissionRepository = _unitOfWork.GetRepository(); - // get the user to update - Result getUserResult = await userRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure || getUserResult.Value is null) return DomainErrors.Users.UserDoesNotExist; @@ -79,7 +74,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler> getAllUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); if (getAllUsersResult.IsFailure) return getAllUsersResult.Errors; @@ -98,7 +93,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler> getPermissionsResult = - await permissionRepository.GetByIdsAsync(command.Permissions, cancellationToken).ConfigureAwait(false); + await _unitOfWork.PermissionRepository.GetByIdsAsync(command.Permissions, cancellationToken).ConfigureAwait(false); if (getPermissionsResult.IsFailure) return getPermissionsResult.Errors; @@ -127,18 +122,18 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler new UserPermissionEntity + UserPermissions = [.. command.Permissions.Select(permissionId => new UserPermissionEntity { UserId = userToUpdate.Id, PermissionId = permissionId, Permission = getPermissionsResult.Value.First(permission => permission.Id == permissionId), User = userToUpdate - }).ToList(), + })], LibraryScans = userToUpdate.LibraryScans }; // save changes and return result - Result updateResult = await userRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false); + Result updateResult = await _unitOfWork.UserRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false); if (updateResult.IsFailure) return updateResult.Errors; diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs index 1e8c61b9..2fc401e9 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs @@ -23,9 +23,9 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserP /// public class GetUserPermissionsQueryHandler : IQueryHandler>> { + private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; - private readonly IUserRepository _userRepository; private readonly IValidator _validator; /// @@ -39,7 +39,7 @@ public class GetUserPermissionsQueryHandler : IQueryHandler(); + _unitOfWork = unitOfWork; _validator = validator; } @@ -62,7 +62,7 @@ public class GetUserPermissionsQueryHandler : IQueryHandler getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs index 992f1d71..00a8460c 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs @@ -22,9 +22,9 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserR /// public class GetUserRoleQueryHandler : IQueryHandler> { + private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; private readonly IAuthorizationService _authorizationService; - private readonly IUserRepository _userRepository; private readonly IValidator _validator; /// @@ -38,7 +38,7 @@ public class GetUserRoleQueryHandler : IQueryHandler(); + _unitOfWork = unitOfWork; _validator = validator; } @@ -61,7 +61,7 @@ public class GetUserRoleQueryHandler : IQueryHandler getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) diff --git a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs index 02623614..fe87e21c 100644 --- a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs +++ b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs @@ -1,18 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Repositories.Common.Base; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; using Lumina.DataAccess.Common.Interceptors; -using Lumina.DataAccess.Core.Repositories.Common.Factory; using Lumina.DataAccess.Core.Seed; using Lumina.DataAccess.Core.UoW; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; -using System.Linq; using System.Reflection; #endregion @@ -41,28 +37,6 @@ public static class DataAccessLayerServices }); services.AddScoped(); services.AddScoped(); - - Type[]? dataAccessLayerTypes = Assembly.GetExecutingAssembly().GetTypes(); - Type? genericRepositoryType = typeof(IRepository<>); - Type? repositoryFactoryType = typeof(RepositoryFactory); - Type? iRepositoryFactoryType = typeof(IRepositoryFactory); - - services.AddScoped(iRepositoryFactoryType!, repositoryFactoryType!); - - // get all classes implementing IRepository (all repository classes) and register them as their corresponding repository interface - IEnumerable repositoryTypes = dataAccessLayerTypes.Where(type => !type.IsInterface && - type.GetInterfaces() - .Any(type => type.IsGenericType && - type.GetGenericTypeDefinition() == genericRepositoryType)); - foreach (Type type in repositoryTypes) - { - services.AddScoped(type.GetInterfaces() // TODO: change to scoped when DbContext is implemented - .Where(type => !type.IsGenericType && - type.GetInterfaces() - .Any(type => type.GetGenericTypeDefinition() == genericRepositoryType)) - .First(), type); - } - services.AddScoped(); } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Common/Factory/IRepositoryFactory.cs b/src/Lumina.DataAccess/Core/Repositories/Common/Factory/IRepositoryFactory.cs deleted file mode 100644 index 92336b33..00000000 --- a/src/Lumina.DataAccess/Core/Repositories/Common/Factory/IRepositoryFactory.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Lumina.DataAccess.Core.Repositories.Common.Factory; - -/// -/// Interface for the repositories factory. -/// -public interface IRepositoryFactory -{ - /// - /// Creates a new repository of type . - /// - /// The type of repository to create. - /// A repository of type . - /// Thrown when the type of the requested repository has not been registered. - TRepository CreateRepository() where TRepository : notnull; -} diff --git a/src/Lumina.DataAccess/Core/Repositories/Common/Factory/RepositoryDictionary.cs b/src/Lumina.DataAccess/Core/Repositories/Common/Factory/RepositoryDictionary.cs deleted file mode 100644 index 307beb60..00000000 --- a/src/Lumina.DataAccess/Core/Repositories/Common/Factory/RepositoryDictionary.cs +++ /dev/null @@ -1,64 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Repositories.Common.Base; -using System; -using System.Collections.Generic; -using System.Linq; -#endregion - -namespace Lumina.DataAccess.Core.Repositories.Common.Factory; - -/// -/// Custom collection for storing repositories. -/// -public class RepositoryDictionary -{ - private readonly List> _container = []; - - /// - /// Gets the number of added repositories. - /// - public int Count => _container.Count; - - /// - /// Resets the collection of repositories. - /// - public void Clear() - { - _container.Clear(); - } - - /// - /// Adds a repository of type to the collection. - /// - /// The type of the repository to add to the collection. - /// The repository to add. - public void Add(TParam value) where TParam : notnull - { - // enforce adding rules - if (value == null) - throw new ArgumentException("Value cannot be null!"); - if (_container.Any(e => e.Key == value.GetType())) - throw new ArgumentException("Duplicate values are not allowed!"); - // check if the value implements an interface that implements IRepository - bool implementsRepository = value.GetType() - .GetInterfaces() - .Any(e => e.GetInterfaces() - .Any(i => i.IsGenericType && - i.GetGenericTypeDefinition() == typeof(IRepository<>))); - if (implementsRepository) - _container.Add(new KeyValuePair(value.GetType(), value)); - else - throw new ArgumentException("Value must implement IRepository interface!"); - } - - /// - /// Gets a repository of type from the collection. - /// - /// The type of the repository interface to get from the collection. - /// The concrete type of the repository interface to get. - /// A repository implementing . - public TResult Get(Type key) - { - return (TResult)_container.FirstOrDefault(e => e.Key == key).Value; - } -} diff --git a/src/Lumina.DataAccess/Core/Repositories/Common/Factory/RepositoryFactory.cs b/src/Lumina.DataAccess/Core/Repositories/Common/Factory/RepositoryFactory.cs deleted file mode 100644 index 52172887..00000000 --- a/src/Lumina.DataAccess/Core/Repositories/Common/Factory/RepositoryFactory.cs +++ /dev/null @@ -1,34 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Microsoft.Extensions.DependencyInjection; -using System; -#endregion - -namespace Lumina.DataAccess.Core.Repositories.Common.Factory; - -/// -/// Concrete implementation for the repositories factory. -/// -public class RepositoryFactory : IRepositoryFactory -{ - private readonly IServiceProvider _serviceProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The service provider. - public RepositoryFactory(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - - /// - /// Creates a new repository of type . - /// - /// The type of repository to create. - /// A repository of type . - /// Thrown when the type of the requested repository has not been registered. - public TRepository CreateRepository() where TRepository : notnull - { - return _serviceProvider.GetRequiredService() ?? throw new ArgumentException(); - } -} diff --git a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs index 0be13ad4..6caf0fea 100644 --- a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs +++ b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs @@ -44,7 +44,6 @@ public class DataSeedService : IDataSeedService /// An representing either a successful operation, or an error. public async Task> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken) { - IPermissionRepository permissionRepository = _unitOfWork.GetRepository(); // create the default authorization permissions and add them to the repository. PermissionEntity[] defaultPermissions = [ @@ -55,7 +54,7 @@ public class DataSeedService : IDataSeedService ]; foreach (PermissionEntity permission in defaultPermissions) { - Result insertPermissionResult = await permissionRepository.InsertAsync(permission, cancellationToken).ConfigureAwait(false); + Result insertPermissionResult = await _unitOfWork.PermissionRepository.InsertAsync(permission, cancellationToken).ConfigureAwait(false); if (insertPermissionResult.IsFailure) return insertPermissionResult.Errors; } @@ -71,8 +70,6 @@ public class DataSeedService : IDataSeedService /// An representing either a successful operation, or an error. public async Task> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken) { - IRoleRepository roleRepository = _unitOfWork.GetRepository(); - // create the default authorization roles and add them to the repository RoleEntity[] defaultRoles = [ @@ -80,7 +77,7 @@ public class DataSeedService : IDataSeedService ]; foreach (RoleEntity role in defaultRoles) { - Result insertRoleResult = await roleRepository.InsertAsync(role, cancellationToken).ConfigureAwait(false); + Result insertRoleResult = await _unitOfWork.RoleRepository.InsertAsync(role, cancellationToken).ConfigureAwait(false); if (insertRoleResult.IsFailure) return insertRoleResult.Errors; } @@ -96,12 +93,8 @@ public class DataSeedService : IDataSeedService /// An representing either a successful operation, or an error. public async Task> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken) { - IRolePermissionRepository rolePermissionRepository = _unitOfWork.GetRepository(); - IRoleRepository roleRepository = _unitOfWork.GetRepository(); - IPermissionRepository permissionRepository = _unitOfWork.GetRepository(); - // get the admin role - Result getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); + Result getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); if (getAdminRoleResult.IsFailure) return getAdminRoleResult.Errors; @@ -109,7 +102,7 @@ public class DataSeedService : IDataSeedService return Errors.Authorization.AdminAccountNotFound; // get all permissions - Result> getPermissionsResult = await permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); if (getPermissionsResult.IsFailure) return getPermissionsResult.Errors; @@ -125,7 +118,7 @@ public class DataSeedService : IDataSeedService CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow }; - Result insertRolePermissionResult = await rolePermissionRepository.InsertAsync(rolePermissionEntity, cancellationToken).ConfigureAwait(false); + Result insertRolePermissionResult = await _unitOfWork.RolePermissionRepository.InsertAsync(rolePermissionEntity, cancellationToken).ConfigureAwait(false); if (insertRolePermissionResult.IsFailure) return insertRolePermissionResult.Errors; } @@ -141,13 +134,8 @@ public class DataSeedService : IDataSeedService /// An representing either a successful operation, or an error. public async Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken) { - IUserRoleRepository userRoleRepository = _unitOfWork.GetRepository(); - IRoleRepository roleRepository = _unitOfWork.GetRepository(); - IUserRepository userRepository = _unitOfWork.GetRepository(); - - // get the admin role - Result getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); + Result getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); if (getAdminRoleResult.IsFailure) return getAdminRoleResult.Errors; @@ -155,7 +143,7 @@ public class DataSeedService : IDataSeedService return Errors.Authorization.AdminRoleNotFound; // get admin user - Result getUserResult = await userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; @@ -172,7 +160,7 @@ public class DataSeedService : IDataSeedService User = getUserResult.Value, UserId = getUserResult.Value.Id }; - Result insertUserRoleResult = await userRoleRepository.InsertAsync(userRole, cancellationToken).ConfigureAwait(false); + Result insertUserRoleResult = await _unitOfWork.UserRoleRepository.InsertAsync(userRole, cancellationToken).ConfigureAwait(false); if (insertUserRoleResult.IsFailure) return insertUserRoleResult.Errors; diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index 939bde62..1af080f0 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -1,11 +1,17 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Application.Common.DataAccess.Repositories.Authorization; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.DataAccess.Core.Repositories.Common.Factory; +using Lumina.DataAccess.Core.Repositories.Authorization; +using Lumina.DataAccess.Core.Repositories.Books; +using Lumina.DataAccess.Core.Repositories.Libraries; +using Lumina.DataAccess.Core.Repositories.Plugins; +using Lumina.DataAccess.Core.Repositories.Users; +using Microsoft.EntityFrameworkCore.Storage; using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; using System.Threading; using System.Threading.Tasks; #endregion @@ -15,79 +21,188 @@ namespace Lumina.DataAccess.Core.UoW; /// /// Interaction boundary with the Data Access Layer. /// -public class UnitOfWork : IUnitOfWork +public class UnitOfWork : IUnitOfWork, IDisposable { private readonly LuminaDbContext _luminaDbContext; - private readonly IRepositoryFactory _repositoryFactory; + private IDbContextTransaction? _transaction; + + private IPermissionRepository? _permissionRepository; + private IRolePermissionRepository? _rolePermissionRepository; + private IRoleRepository? _roleRepository; + private IUserRoleRepository? _userRoleRepository; + private IBookRepository? _bookRepository; + private IDirectoryScanFingerprintRepository? _directoryScanFingerprintRepository; + private ILibraryRepository? _libraryRepository; + private ILibraryScanRepository? _libraryScanRepository; + private ILibraryScanSnapshotRepository? _libraryScanSnapshotRepository; + private ILibraryScanStagingResultsRepository? _libraryScanStagingResultsRepository; + private ILibraryMetadataProviderConfigurationRepository? _libraryMetadataProviderConfigurationRepository; + private IPluginRepository? _pluginRepository; + private IUserRepository? _userRepository; /// - /// Gets or sets the collection of available repositories. + /// Gets the permission repository. /// - internal RepositoryDictionary Repositories { get; private set; } = new RepositoryDictionary(); - - /// - /// Initializes a new instance of the class. - /// - /// The factory used to generate repositories. - /// Injected Entity Framework DbContext. - public UnitOfWork(IRepositoryFactory repositoryFactory, LuminaDbContext luminaDbContext) + public IPermissionRepository PermissionRepository { - _repositoryFactory = repositoryFactory; - _luminaDbContext = luminaDbContext; - AddRepositories(); - } - - /// - /// Adds all the repositories from the Data Access Layer so that they can be exposed to the Business Layer. - /// - internal void AddRepositories() - { - // get all the concrete implementations of IRepository<> - IEnumerable repositoryClassTypes = - Assembly.GetExecutingAssembly() - .GetTypes() - .Where(t => !t.IsInterface && !t.IsAbstract && t.GetInterfaces() - .Any(i => i.IsGenericType && - i.GetGenericTypeDefinition() == typeof(IRepository<>))); - // store all repositories - foreach (Type repositoryClassType in repositoryClassTypes) + get { - // get the interface that implements IRepository<> of the currently iterated repository class - Type repositoryInterfaceType = repositoryClassType.GetInterfaces() - .Where(i => !i.IsGenericType && - i.GetInterfaces() - .Any(a => a.GetGenericTypeDefinition() == typeof(IRepository<>))) - .First(); - // ask the concrete type for the repository interface type from the repositories factory; - // because the method for creating a repository is generic and we need to call it with a runtime type, reflection is the only option - object repositoryClass = typeof(IRepositoryFactory).GetMethod("CreateRepository")! - .MakeGenericMethod(repositoryInterfaceType) - .Invoke(_repositoryFactory, null)!; - Repositories.Add(repositoryClass); + _permissionRepository ??= new PermissionRepository(_luminaDbContext); + return _permissionRepository; } } /// - /// Exposes a repository of type to the Business Logic Layer. + /// Gets the role permission repository. /// - /// The type of the exposed repository. - /// A repository of type . - public TRepository GetRepository() + public IRolePermissionRepository RolePermissionRepository { - // get the repository type based on the type of the provided repository interface - Type repositoryType = Assembly.GetExecutingAssembly() - .GetTypes() - .Where(type => !type.IsInterface && !type.IsAbstract && typeof(TRepository).IsAssignableFrom(type)) - .First(); - return Repositories.Get(repositoryType); + get + { + _rolePermissionRepository ??= new RolePermissionRepository(_luminaDbContext); + return _rolePermissionRepository; + } } /// - /// Resets the list of repositories. + /// Gets the role repository. /// - internal void ResetRepositories() + public IRoleRepository RoleRepository { - Repositories.Clear(); + get + { + _roleRepository ??= new RoleRepository(_luminaDbContext); + return _roleRepository; + } + } + + /// + /// Gets the user role repository. + /// + public IUserRoleRepository UserRoleRepository + { + get + { + _userRoleRepository ??= new UserRoleRepository(_luminaDbContext); + return _userRoleRepository; + } + } + + /// + /// Gets the book repository. + /// + public IBookRepository BookRepository + { + get + { + _bookRepository ??= new BookRepository(_luminaDbContext); + return _bookRepository; + } + } + + /// + /// Gets the directory scan fingerprint repository. + /// + public IDirectoryScanFingerprintRepository DirectoryScanFingerprintRepository + { + get + { + _directoryScanFingerprintRepository ??= new DirectoryScanFingerprintRepository(_luminaDbContext); + return _directoryScanFingerprintRepository; + } + } + + /// + /// Gets the library repository. + /// + public ILibraryRepository LibraryRepository + { + get + { + _libraryRepository ??= new LibraryRepository(_luminaDbContext); + return _libraryRepository; + } + } + + /// + /// Gets the library scan repository. + /// + public ILibraryScanRepository LibraryScanRepository + { + get + { + _libraryScanRepository ??= new LibraryScanRepository(_luminaDbContext); + return _libraryScanRepository; + } + } + + /// + /// Gets the library scan snapshot repository. + /// + public ILibraryScanSnapshotRepository LibraryScanSnapshotRepository + { + get + { + _libraryScanSnapshotRepository ??= new LibraryScanSnapshotRepository(_luminaDbContext); + return _libraryScanSnapshotRepository; + } + } + + /// + /// Gets the library scan staging results repository. + /// + public ILibraryScanStagingResultsRepository LibraryScanStagingResultsRepository + { + get + { + _libraryScanStagingResultsRepository ??= new LibraryScanStagingResultsRepository(_luminaDbContext); + return _libraryScanStagingResultsRepository; + } + } + + /// + /// Gets the library metadata provider configuration repository. + /// + public ILibraryMetadataProviderConfigurationRepository LibraryMetadataProviderConfigurationRepository + { + get + { + _libraryMetadataProviderConfigurationRepository ??= new LibraryMetadataProviderConfigurationRepository(_luminaDbContext); + return _libraryMetadataProviderConfigurationRepository; + } + } + + /// + /// Gets the plugin repository. + /// + public IPluginRepository PluginRepository + { + get + { + _pluginRepository ??= new PluginRepository(_luminaDbContext); + return _pluginRepository; + } + } + + /// + /// Gets the user repository. + /// + public IUserRepository UserRepository + { + get + { + _userRepository ??= new UserRepository(_luminaDbContext); + return _userRepository; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public UnitOfWork(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; } /// @@ -100,18 +215,51 @@ public class UnitOfWork : IUnitOfWork } /// - /// Opens a transaction. + /// Begins a new database transaction. /// - public void OpenTransaction() + /// Cancellation token that can be used to stop the execution. + /// A task representing the asynchronous operation. + public async Task BeginTransactionAsync(CancellationToken cancellationToken) { - throw new NotImplementedException(); + _transaction = await _luminaDbContext.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); } /// - /// Commits a transaction. + /// Commits the current transaction. /// - public void CommitTransaction() + /// Cancellation token that can be used to stop the execution. + /// A task representing the asynchronous operation. + public async Task CommitTransactionAsync(CancellationToken cancellationToken) { - throw new NotImplementedException(); + if (_transaction is not null) + { + await _transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + await _transaction.DisposeAsync().ConfigureAwait(false); + _transaction = null; + } + } + + /// + /// Rolls back the current transaction. + /// + /// Cancellation token that can be used to stop the execution. + /// A task representing the asynchronous operation. + public async Task RollbackTransactionAsync(CancellationToken cancellationToken) + { + if (_transaction is not null) + { + await _transaction.RollbackAsync(cancellationToken).ConfigureAwait(false); + await _transaction.DisposeAsync().ConfigureAwait(false); + _transaction = null; + } + } + + /// + /// Disposes the unit of work and its resources. + /// + public void Dispose() + { + _transaction?.Dispose(); + _luminaDbContext.Dispose(); } } diff --git a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs index be8a5cd3..581e6ea9 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs @@ -23,7 +23,7 @@ namespace Lumina.Infrastructure.Core.Authorization; /// public class AuthorizationService : IAuthorizationService { - private readonly IUserRepository _userRepository; + private readonly IUnitOfWork _unitOfWork; private readonly IAuthorizationPolicyFactory _authorizationPolicyFactory; /// @@ -33,7 +33,7 @@ public class AuthorizationService : IAuthorizationService /// The factory used to generate authorization policies. public AuthorizationService(IUnitOfWork unitOfWork, IAuthorizationPolicyFactory authorizationPolicyFactory) { - _userRepository = unitOfWork.GetRepository(); + _unitOfWork = unitOfWork; _authorizationPolicyFactory = authorizationPolicyFactory; } @@ -46,7 +46,7 @@ public class AuthorizationService : IAuthorizationService /// if the user has the specified permission, otherwise. public async Task HasPermissionAsync(Guid userId, AuthorizationPermission permission, CancellationToken cancellationToken) { - Result getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure || getUserResult.Value is null) return false; @@ -68,7 +68,7 @@ public class AuthorizationService : IAuthorizationService /// if the user is in the specified role, otherwise. public async Task IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken) { - Result getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure || getUserResult.Value is null) return false; return getUserResult.Value.UserRole?.Role.RoleName == role; @@ -96,7 +96,7 @@ public class AuthorizationService : IAuthorizationService /// An containing either a , or an error. public async Task> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken) { - Result getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; @@ -108,9 +108,7 @@ public class AuthorizationService : IAuthorizationService string? role = getUserResult.Value.UserRole?.Role.RoleName; // get direct user permissions - HashSet directPermissions = getUserResult.Value.UserPermissions - .Select(userPermission => userPermission.Permission.PermissionName) - .ToHashSet(); + HashSet directPermissions = [.. getUserResult.Value.UserPermissions.Select(userPermission => userPermission.Permission.PermissionName)]; // get permissions from roles HashSet? rolePermissions = getUserResult.Value.UserRole?.Role.RolePermissions diff --git a/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs b/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs index 9ce98ec6..eaaf46e1 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs @@ -17,7 +17,7 @@ namespace Lumina.Infrastructure.Core.Authorization.Policies.Over18; /// public class Over18Policy : IOver18Policy { - private readonly IUserRepository _userRepository; + private readonly IUnitOfWork _unitOfWork; private readonly IDateTimeProvider _dateTimeProvider; /// @@ -27,7 +27,7 @@ public class Over18Policy : IOver18Policy /// Injected service for time related functionality. public Over18Policy(IUnitOfWork unitOfWork, IDateTimeProvider dateTimeProvider) { - _userRepository = unitOfWork.GetRepository(); + _unitOfWork = unitOfWork; _dateTimeProvider = dateTimeProvider; } @@ -39,7 +39,7 @@ public class Over18Policy : IOver18Policy /// if the policy evaluation succeeds, otherwise. public async Task EvaluateAsync(Guid userId, CancellationToken cancellationToken) { - Result getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure || getUserResult.Value is null) return false; diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs index 97931b63..28c39806 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs @@ -59,7 +59,7 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); @@ -69,7 +69,7 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); // mark the staging results against the media library scan snapshot of the previous scan - Result markChangesResult = await stagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false); + Result markChangesResult = await unitOfWork.LibraryScanStagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false); if (markChangesResult.IsFailure) throw new InvalidOperationException(markChangesResult.FirstError.Description); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs index c983bcc9..8f334a8c 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs @@ -63,13 +63,13 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); + IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // count the files that need hashing, for progress reporting purposes - Result getFilesToHashCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); + Result getFilesToHashCountResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); if (getFilesToHashCountResult.IsFailure) throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description); int totalFilesToHash = getFilesToHashCountResult.Value; @@ -89,7 +89,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra { cancellationToken.ThrowIfCancellationRequested(); - Result> getFilesToHashPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + Result> getFilesToHashPageResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false); if (getFilesToHashPageResult.IsFailure) throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description); IReadOnlyList filesToHashPage = getFilesToHashPageResult.Value; @@ -112,7 +112,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra }, cancellationToken).ConfigureAwait(false); // write the computed hashes back to the staging results - Result updateHashesResult = await stagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false); + Result updateHashesResult = await unitOfWork.LibraryScanStagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false); if (updateHashesResult.IsFailure) throw new InvalidOperationException(updateHashesResult.FirstError.Description); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs index bd152ae3..2f650ac8 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs @@ -1,14 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Books; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; @@ -75,13 +74,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryMetadataProviderConfigurationRepository configurationRepository = unitOfWork.GetRepository(); - IBookRepository bookRepository = unitOfWork.GetRepository(); - + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the metadata providers configured for the media library, in their configured order, that support the media library type - Result> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + Result> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) throw new InvalidOperationException(getConfigurationsResult.FirstError.Description); List providers = []; @@ -96,7 +93,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } // count the books that need their metadata enriched, for progress reporting purposes - Result getBooksToEnrichCountResult = await bookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getBooksToEnrichCountResult.IsFailure) throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); int totalBooksToEnrich = getBooksToEnrichCountResult.Value; @@ -116,7 +113,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo { cancellationToken.ThrowIfCancellationRequested(); - Result> getBooksPageResult = await bookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); if (getBooksPageResult.IsFailure) throw new InvalidOperationException(getBooksPageResult.FirstError.Description); IReadOnlyList booksPage = getBooksPageResult.Value; @@ -127,7 +124,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo { cancellationToken.ThrowIfCancellationRequested(); - await EnrichBookAsync(bookEntity, providers, bookRepository, cancellationToken).ConfigureAwait(false); + await EnrichBookAsync(bookEntity, providers, unitOfWork.BookRepository, cancellationToken).ConfigureAwait(false); // check if enough time has passed since last update DateTime now = DateTime.UtcNow; diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs index 7513b0e5..bdf3646e 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs @@ -66,7 +66,7 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryScanSnapshotRepository libraryScanSnapshotRepository = unitOfWork.GetRepository(); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); @@ -76,12 +76,12 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); // get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them - Result> getDeletedPathsResult = await libraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false); + Result> getDeletedPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false); if (getDeletedPathsResult.IsFailure) throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description); // apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan - Result applySnapshotSwapResult = await libraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false); + Result applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false); if (applySnapshotSwapResult.IsFailure) throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description); @@ -93,21 +93,21 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed } // materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata - Result> getPathsResult = await libraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + Result> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getPathsResult.IsFailure) throw new InvalidOperationException(getPathsResult.FirstError.Description); - IBookRepository bookRepository = unitOfWork.GetRepository(); + foreach (string path in getPathsResult.Value) { cancellationToken.ThrowIfCancellationRequested(); - Result getExistingBookResult = await bookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false); + Result getExistingBookResult = await unitOfWork.BookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false); if (getExistingBookResult.IsFailure) throw new InvalidOperationException(getExistingBookResult.FirstError.Description); if (getExistingBookResult.Value is not null) continue; - Result insertBookResult = await bookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false); + Result insertBookResult = await unitOfWork.BookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false); if (insertBookResult.IsFailure) throw new InvalidOperationException(insertBookResult.FirstError.Description); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs index 86af2b48..c252b167 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs @@ -79,14 +79,11 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryRepository libraryRepository = unitOfWork.GetRepository()!; - ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); - IDirectoryScanFingerprintRepository directoryScanFingerprintRepository = unitOfWork.GetRepository(); MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the library from the repository - Result getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure || getLibraryResult.Value is null) throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); @@ -99,7 +96,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF Dictionary? fingerprintsByPath = null; if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan) { - Result> getFingerprintsResult = await directoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + Result> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getFingerprintsResult.IsFailure) throw new InvalidOperationException(getFingerprintsResult.FirstError.Description); fingerprintsByPath = getFingerprintsResult.Value; @@ -128,8 +125,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF fingerprintsByPath, stagingBatch, fingerprintBatch, - stagingResultsRepository, - directoryScanFingerprintRepository, + unitOfWork.LibraryScanStagingResultsRepository, + unitOfWork.DirectoryScanFingerprintRepository, cancellationToken).ConfigureAwait(false); processedContentLocations++; @@ -148,13 +145,13 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF // flush any remaining discovered files and directory scan fingerprints that did not reach the batch size if (stagingBatch.Count > 0) { - Result insertResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); + Result insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); if (insertResult.IsFailure) throw new InvalidOperationException(insertResult.FirstError.Description); } if (fingerprintBatch.Count > 0) { - Result upsertResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); + Result upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false); if (upsertResult.IsFailure) throw new InvalidOperationException(upsertResult.FirstError.Description); } diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs index b8aa903e..ce5c3a04 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs @@ -50,7 +50,6 @@ internal sealed class PluginDetectionSyncJob : BackgroundService await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService(); - IPluginRepository pluginRepository = unitOfWork.GetRepository(); foreach (IPlugin plugin in _pluginManager.GetPlugins()) { @@ -66,7 +65,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService CreatedBy = default, UpdatedBy = default }; - Result upsertResult = await pluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false); + Result upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false); if (upsertResult.IsFailure) _logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", plugin.Name, upsertResult.FirstError.Description); } diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs index 6eb5a33f..7ea232c1 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs @@ -36,8 +36,7 @@ internal sealed class PluginSettingsStore : IPluginSettingsStore /// public async Task?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken) { - IPluginRepository pluginRepository = _unitOfWork.GetRepository(); - Result getPluginResult = await pluginRepository.GetByIdAsync(pluginId, cancellationToken).ConfigureAwait(false); + Result getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(pluginId, cancellationToken).ConfigureAwait(false); if (getPluginResult.IsFailure) { _logger.LogWarning("Failed to read the settings of the plugin with Id '{PluginId}': {Error}", pluginId, getPluginResult.FirstError.Description); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs index 839ef23b..9bf8c1ea 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs @@ -45,7 +45,7 @@ public class GetPermissionsQueryHandlerTests _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); - _mockUnitOfWork.GetRepository().Returns(_mockPermissionRepository); + _mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository); _sut = new GetPermissionsQueryHandler( _mockAuthorizationService, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs index 85dd0206..1b2ade05 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs @@ -51,7 +51,7 @@ public class AddRoleCommandHandlerTests _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); - _mockUnitOfWork.GetRepository().Returns(_mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository); _sut = new AddRoleCommandHandler( _mockAuthorizationService, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs index 6f572422..6f313560 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs @@ -48,7 +48,7 @@ public class DeleteRoleCommandHandlerTests _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); - _mockUnitOfWork.GetRepository().Returns(_mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository); _sut = new DeleteRoleCommandHandler( _mockAuthorizationService, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs index 04ee7836..748957f9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs @@ -51,7 +51,7 @@ public class UpdateRoleCommandHandlerTests _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); - _mockUnitOfWork.GetRepository().Returns(_mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository); _sut = new UpdateRoleCommandHandler( _mockAuthorizationService, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs index c51c2caf..d1807feb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs @@ -50,7 +50,7 @@ public class GetRolePermissionsQueryHandlerTests _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); - _mockUnitOfWork.GetRepository().Returns(_mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository); _sut = new GetRolePermissionsQueryHandler( _mockAuthorizationService, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs index bcf6ae4e..8333ce72 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs @@ -46,7 +46,7 @@ public class GetRolesQueryHandlerTests _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); - _mockUnitOfWork.GetRepository().Returns(_mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository); _sut = new GetRolesQueryHandler( _mockAuthorizationService, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs index b25800b3..d1a9270b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs @@ -58,7 +58,7 @@ public class SetupApplicationCommandHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); - _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); _mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow); _sut = new SetupApplicationCommandHandler( diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs index a0f9cf1f..83e84a03 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitiliazation/CheckInitializationQueryHandlerTests.cs @@ -34,7 +34,7 @@ public class CheckInitializationQueryHandlerTests _mockUnitOfWork = Substitute.For(); _mockUserRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); _sut = new CheckInitializationQueryHandler(_mockUnitOfWork); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs index 7ec8e91a..6850e325 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs @@ -47,7 +47,7 @@ public class AddBookCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockBookRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(_mockBookRepository); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs index a1b432dc..c7e3ed50 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs @@ -31,7 +31,7 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests { _mockUnitOfWork = Substitute.For(); _mockConfigurationRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(_mockConfigurationRepository); + _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) .Returns([]); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs index 1c449a57..ad8f489c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs @@ -30,7 +30,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests { _mockUnitOfWork = Substitute.For(); _mockConfigurationRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(_mockConfigurationRepository); + _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) .Returns([]); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs index 32727552..aeec76ed 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs @@ -29,7 +29,7 @@ public class UpdatePluginSettingsCommandHandlerTests { _mockUnitOfWork = Substitute.For(); _mockPluginRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(_mockPluginRepository); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) .Returns([]); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs index f54e2a98..c9540616 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs @@ -30,7 +30,7 @@ public class GetPluginsQueryHandlerTests { _mockUnitOfWork = Substitute.For(); _mockPluginRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(_mockPluginRepository); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _sut = new GetPluginsQueryHandler(_mockUnitOfWork); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs index 59a92aac..8b4646c5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs @@ -38,7 +38,7 @@ public class ChangePasswordCommandHandlerTests _mockHashService = Substitute.For(); _mockUserRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs index 327a1cad..7a9923fb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs @@ -43,7 +43,7 @@ public class RecoverPasswordCommandHandlerTests _mockCryptographyService = Substitute.For(); _mockUserRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs index 4df769f2..1c95f5b0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs @@ -49,7 +49,7 @@ public class RegisterUserCommandHandlerTests _mockUserRepository = Substitute.For(); _mockDateTimeProvider = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); _mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow); IValidator mockValidator = Substitute.For>(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs index e0a7aa41..be1e390a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs @@ -48,7 +48,7 @@ public class GetUsersQueryHandlerTests _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); - _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); _sut = new GetUsersQueryHandler( _mockAuthorizationService, diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs index 4a041d28..e2646382 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs @@ -48,7 +48,7 @@ public class LoginUserQueryHandlerTests _mockUserRepository = Substitute.For(); _mockDateTimeProvider = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); _mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow); IValidator mockValidator = Substitute.For>(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs index 7fda416b..1a4743ce 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs @@ -57,9 +57,9 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); - _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); - _mockUnitOfWork.GetRepository().Returns(_mockRoleRepository); - _mockUnitOfWork.GetRepository().Returns(_mockPermissionRepository); + _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); + _mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository); + _mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs index 462d0491..4477dbeb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs @@ -49,7 +49,7 @@ public class GetUserPermissionsQueryHandlerTests _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); - _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs index 39f3f7ee..1d14308d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs @@ -47,7 +47,7 @@ public class GetUserRoleQueryHandlerTests _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); - _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/DependencyInjection/DataAccessLayerServicesTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/DependencyInjection/DataAccessLayerServicesTests.cs index 06d7c2bf..5c9f6491 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/DependencyInjection/DataAccessLayerServicesTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/DependencyInjection/DataAccessLayerServicesTests.cs @@ -1,11 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Time; using Lumina.DataAccess.Common.DependencyInjection; -using Lumina.DataAccess.Core.Repositories.Books; -using Lumina.DataAccess.Core.Repositories.Common.Factory; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Common.Setup; using Microsoft.EntityFrameworkCore; @@ -36,8 +33,6 @@ public class DataAccessLayerServicesTests // Assert Assert.Contains(services, sd => sd.ServiceType == typeof(LuminaDbContext)); Assert.Contains(services, sd => sd.ServiceType == typeof(IUnitOfWork) && sd.ImplementationType == typeof(UnitOfWork)); - Assert.Contains(services, sd => sd.ServiceType == typeof(IRepositoryFactory) && sd.ImplementationType == typeof(RepositoryFactory)); - Assert.Contains(services, sd => sd.ServiceType == typeof(IBookRepository) && sd.ImplementationType == typeof(BookRepository)); } [Fact] @@ -62,7 +57,7 @@ public class DataAccessLayerServicesTests } [Fact] - public void AddDataAccessLayerServices_WhenCalled_ShouldRegisterRepositories() + public void AddDataAccessLayerServices_WhenCalled_ShouldExposeRepositoriesThroughUnitOfWork() { // Arrange ServiceCollection services = new(); @@ -72,11 +67,12 @@ public class DataAccessLayerServicesTests services.AddTransient(); services.AddTransient(); - + ServiceProvider serviceProvider = services.BuildServiceProvider(); // Assert - IBookRepository? repository = serviceProvider.GetService(); - Assert.NotNull(repository); + IUnitOfWork unitOfWork = serviceProvider.GetRequiredService(); + Assert.NotNull(unitOfWork.BookRepository); + Assert.NotNull(unitOfWork.PermissionRepository); } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/Fixtures/IUnregisteredRepository.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/Fixtures/IUnregisteredRepository.cs deleted file mode 100644 index df416543..00000000 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/Fixtures/IUnregisteredRepository.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory.Fixtures; - -/// -/// Repository fixture interface for testing non registered repositories. -/// -public interface IUnregisteredRepository { } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryDictionaryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryDictionaryTests.cs deleted file mode 100644 index c1403a77..00000000 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryDictionaryTests.cs +++ /dev/null @@ -1,107 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; -using Lumina.Application.Common.DataAccess.Repositories.Books; -using Lumina.DataAccess.Core.Repositories.Books; -using Lumina.DataAccess.Core.Repositories.Common.Factory; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class RepositoryDictionaryTests -{ - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public RepositoryDictionaryTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } - - [Fact] - public void Add_WhenValidRepositoryItemIsAdded_ShouldIncreaseCount() - { - // Arrange - BookRepository bookRepository = _fixture.Create(); - RepositoryDictionary repositoryDictionary = new(); - - // Act - repositoryDictionary.Add(bookRepository); - - // Assert - Assert.Equal(1, repositoryDictionary.Count); - } - - [Fact] - public void Clear_WhenCalled_ShouldRemoveAllItems() - { - // Arrange - BookRepository bookRepository = _fixture.Create(); - RepositoryDictionary repositoryDictionary = new(); - repositoryDictionary.Add(bookRepository); - - // Act - repositoryDictionary.Clear(); - - // Assert - Assert.Equal(0, repositoryDictionary.Count); - } - - [Fact] - public void Get_WhenRepositoryExists_ShouldReturnCorrectRepository() - { - // Arrange - BookRepository expected = _fixture.Create(); - RepositoryDictionary repositoryDictionary = new(); - repositoryDictionary.Add(expected); - - // Act - IBookRepository actual = repositoryDictionary.Get(typeof(BookRepository)); - - // Assert - Assert.Same(expected, actual); - } - - [Fact] - public void Add_WhenNullValueIsProvided_ShouldThrowArgumentException() - { - // Arrange - RepositoryDictionary repositoryDictionary = new(); - - // Act & Assert - Assert.Throws(() => repositoryDictionary.Add(null!)); - } - - [Fact] - public void Add_WhenDuplicateValueIsAdded_ShouldThrowArgumentException() - { - // Arrange - BookRepository bookRepository = _fixture.Create(); - RepositoryDictionary repositoryDictionary = new(); - repositoryDictionary.Add(bookRepository); - - // Act & Assert - ArgumentException exception = Assert.Throws(() => repositoryDictionary.Add(bookRepository)); - Assert.Equal("Duplicate values are not allowed!", exception.Message); - } - - [Fact] - public void Add_WhenNonRepositoryValueIsAdded_ShouldThrowArgumentException() - { - // Arrange - object nonRepository = new(); - RepositoryDictionary repositoryDictionary = new(); - - // Act & Assert - ArgumentException exception = Assert.Throws(() => repositoryDictionary.Add(nonRepository)); - Assert.Equal("Value must implement IRepository interface!", exception.Message); - } -} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryFactoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryFactoryTests.cs deleted file mode 100644 index 6a329128..00000000 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Common/Factory/RepositoryFactoryTests.cs +++ /dev/null @@ -1,58 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Repositories.Books; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Time; -using Lumina.DataAccess.Common.DependencyInjection; -using Lumina.DataAccess.Core.Repositories.Common.Factory; -using Lumina.DataAccess.UnitTests.Common.Setup; -using Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory.Fixtures; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class RepositoryFactoryTests -{ - [Fact] - public void CreateRepository_WhenCalled_ShouldReturnCorrectRepository() - { - // Arrange - ServiceCollection services = new(); - DataAccessLayerServices.AddDataAccessLayerServices(services); - - services.AddTransient(); - services.AddTransient(); - ServiceProvider serviceProvider = services.BuildServiceProvider(); - RepositoryFactory repositoryFactory = new(serviceProvider); - - // Act - IBookRepository result = repositoryFactory.CreateRepository(); - - // Assert - Assert.NotNull(result); - Assert.IsAssignableFrom(result); - } - - [Fact] - public void CreateRepository_WhenUnregisteredTypeRequested_ShouldThrowException() - { - // Arrange - ServiceCollection services = new(); - DataAccessLayerServices.AddDataAccessLayerServices(services); - ServiceProvider serviceProvider = services.BuildServiceProvider(); - RepositoryFactory repositoryFactory = new(serviceProvider); - - // Act & Assert - InvalidOperationException exception = Assert.Throws( - () => repositoryFactory.CreateRepository()); - Assert.Equal( - "No service for type 'Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory.Fixtures.IUnregisteredRepository' has been registered.", - exception.Message); - } -} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs index fffba1cb..18d4053b 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs @@ -43,7 +43,7 @@ public class DataSeedServiceTests _fixedUtcNow = DateTime.UtcNow; _mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow); - _mockUnitOfWork.GetRepository().Returns(_mockPermissionRepository); + _mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository); _sut = new DataSeedService(_mockUnitOfWork, _mockDateTimeProvider); } @@ -126,7 +126,7 @@ public class DataSeedServiceTests // Arrange Guid userId = Guid.NewGuid(); IRoleRepository mockRoleRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); mockRoleRepository .InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); @@ -156,7 +156,7 @@ public class DataSeedServiceTests // Arrange Guid userId = Guid.NewGuid(); IRoleRepository mockRoleRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); Error expectedError = Error.Conflict("Role.Conflict", "Role already exists"); mockRoleRepository @@ -181,7 +181,7 @@ public class DataSeedServiceTests List capturedRoleNames = []; IRoleRepository mockRoleRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); mockRoleRepository .InsertAsync(Arg.Any(), Arg.Any()) @@ -203,7 +203,7 @@ public class DataSeedServiceTests RoleEntity? capturedRole = null; IRoleRepository mockRoleRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); mockRoleRepository .InsertAsync(Arg.Any(), Arg.Any()) @@ -238,9 +238,9 @@ public class DataSeedServiceTests IPermissionRepository mockPermissionRepository = Substitute.For(); IRolePermissionRepository mockRolePermissionRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); - _mockUnitOfWork.GetRepository().Returns(mockPermissionRepository); - _mockUnitOfWork.GetRepository().Returns(mockRolePermissionRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); + _mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository); + _mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); mockPermissionRepository.GetAllAsync(Arg.Any()).Returns(permissions); @@ -271,7 +271,7 @@ public class DataSeedServiceTests // Arrange Guid userId = Guid.NewGuid(); IRoleRepository mockRoleRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); mockRoleRepository .GetByNameAsync("Admin", Arg.Any()) @@ -297,8 +297,8 @@ public class DataSeedServiceTests IRoleRepository mockRoleRepository = Substitute.For(); IPermissionRepository mockPermissionRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); - _mockUnitOfWork.GetRepository().Returns(mockPermissionRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); + _mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); mockPermissionRepository.GetAllAsync(Arg.Any()).Returns(expectedError); @@ -326,9 +326,9 @@ public class DataSeedServiceTests IPermissionRepository mockPermissionRepository = Substitute.For(); IRolePermissionRepository mockRolePermissionRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); - _mockUnitOfWork.GetRepository().Returns(mockPermissionRepository); - _mockUnitOfWork.GetRepository().Returns(mockRolePermissionRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); + _mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository); + _mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); mockPermissionRepository.GetAllAsync(Arg.Any()).Returns(permissions); @@ -352,7 +352,7 @@ public class DataSeedServiceTests Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role"); IRoleRepository mockRoleRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); mockRoleRepository .GetByNameAsync("Admin", Arg.Any()) @@ -383,9 +383,9 @@ public class DataSeedServiceTests IUserRepository mockUserRepository = Substitute.For(); IUserRoleRepository mockUserRoleRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); - _mockUnitOfWork.GetRepository().Returns(mockUserRepository); - _mockUnitOfWork.GetRepository().Returns(mockUserRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); + _mockUnitOfWork.UserRepository.Returns(mockUserRepository); + _mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns(adminUser); @@ -417,7 +417,7 @@ public class DataSeedServiceTests // Arrange Guid userId = Guid.NewGuid(); IRoleRepository mockRoleRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); mockRoleRepository .GetByNameAsync("Admin", Arg.Any()) @@ -442,8 +442,8 @@ public class DataSeedServiceTests IRoleRepository mockRoleRepository = Substitute.For(); IUserRepository mockUserRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); - _mockUnitOfWork.GetRepository().Returns(mockUserRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); + _mockUnitOfWork.UserRepository.Returns(mockUserRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns((UserEntity?)null); @@ -472,9 +472,9 @@ public class DataSeedServiceTests IUserRepository mockUserRepository = Substitute.For(); IUserRoleRepository mockUserRoleRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); - _mockUnitOfWork.GetRepository().Returns(mockUserRepository); - _mockUnitOfWork.GetRepository().Returns(mockUserRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); + _mockUnitOfWork.UserRepository.Returns(mockUserRepository); + _mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns(adminUser); @@ -498,7 +498,7 @@ public class DataSeedServiceTests Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role"); IRoleRepository mockRoleRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); mockRoleRepository .GetByNameAsync("Admin", Arg.Any()) @@ -525,8 +525,8 @@ public class DataSeedServiceTests IRoleRepository mockRoleRepository = Substitute.For(); IUserRepository mockUserRepository = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(mockRoleRepository); - _mockUnitOfWork.GetRepository().Returns(mockUserRepository); + _mockUnitOfWork.RoleRepository.Returns(mockRoleRepository); + _mockUnitOfWork.UserRepository.Returns(mockUserRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns(expectedError); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs index f50a3ddc..1a7a4780 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs @@ -1,18 +1,22 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; +using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Time; using Lumina.DataAccess.Common.DependencyInjection; -using Lumina.DataAccess.Core.Repositories.Common.Factory; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Common.Setup; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -43,100 +47,50 @@ public class UnitOfWorkTests })); } - [Fact] - public void ResetRepositories_WhenCalled_ShouldClearAllRepositories() + /// + /// Provides the repository properties exposed by the unit of work. + /// + /// An enumerable of tuples containing the repository property name and its accessor. + public static IEnumerable GetRepositoryProperties() { - // Arrange - ServiceCollection services = new(); - DataAccessLayerServices.AddDataAccessLayerServices(services); - services.AddTransient(); - services.AddTransient(); - ServiceProvider serviceProvider = services.BuildServiceProvider(); - UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); - - // Act - unitOfWork.ResetRepositories(); - - // Assert - Assert.Equal(0, unitOfWork.Repositories.Count); + yield return new object[] { nameof(IUnitOfWork.PermissionRepository), (Func)(unitOfWork => unitOfWork.PermissionRepository) }; + yield return new object[] { nameof(IUnitOfWork.RolePermissionRepository), (Func)(unitOfWork => unitOfWork.RolePermissionRepository) }; + yield return new object[] { nameof(IUnitOfWork.RoleRepository), (Func)(unitOfWork => unitOfWork.RoleRepository) }; + yield return new object[] { nameof(IUnitOfWork.UserRoleRepository), (Func)(unitOfWork => unitOfWork.UserRoleRepository) }; + yield return new object[] { nameof(IUnitOfWork.BookRepository), (Func)(unitOfWork => unitOfWork.BookRepository) }; + yield return new object[] { nameof(IUnitOfWork.DirectoryScanFingerprintRepository), (Func)(unitOfWork => unitOfWork.DirectoryScanFingerprintRepository) }; + yield return new object[] { nameof(IUnitOfWork.LibraryRepository), (Func)(unitOfWork => unitOfWork.LibraryRepository) }; + yield return new object[] { nameof(IUnitOfWork.LibraryScanRepository), (Func)(unitOfWork => unitOfWork.LibraryScanRepository) }; + yield return new object[] { nameof(IUnitOfWork.LibraryScanSnapshotRepository), (Func)(unitOfWork => unitOfWork.LibraryScanSnapshotRepository) }; + yield return new object[] { nameof(IUnitOfWork.LibraryScanStagingResultsRepository), (Func)(unitOfWork => unitOfWork.LibraryScanStagingResultsRepository) }; + yield return new object[] { nameof(IUnitOfWork.LibraryMetadataProviderConfigurationRepository), (Func)(unitOfWork => unitOfWork.LibraryMetadataProviderConfigurationRepository) }; + yield return new object[] { nameof(IUnitOfWork.PluginRepository), (Func)(unitOfWork => unitOfWork.PluginRepository) }; + yield return new object[] { nameof(IUnitOfWork.UserRepository), (Func)(unitOfWork => unitOfWork.UserRepository) }; } - [Fact] - public void AddRepositories_WhenCalled_ShouldAddRepositories() + [Theory] + [MemberData(nameof(GetRepositoryProperties))] + public void RepositoryProperty_WhenAccessed_ShouldReturnRepositoryAndCacheInstance(string propertyName, Func repositoryAccessor) { // Arrange - ServiceCollection services = new(); - DataAccessLayerServices.AddDataAccessLayerServices(services); - services.AddTransient(); - services.AddTransient(); - ServiceProvider serviceProvider = services.BuildServiceProvider(); - UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); - int initialCount = unitOfWork.Repositories.Count; + UnitOfWork unitOfWork = CreateUnitOfWork(); // Act - unitOfWork.ResetRepositories(); - unitOfWork.AddRepositories(); + object firstAccess = repositoryAccessor(unitOfWork); + object secondAccess = repositoryAccessor(unitOfWork); // Assert - Assert.True(unitOfWork.Repositories.Count > 0); - Assert.Equal(initialCount, unitOfWork.Repositories.Count); - } - - [Fact] - public void Constructor_WhenCalled_ShouldAddRepositories() - { - // Arrange - IRepositoryFactory repositoryFactory = _fixture.Create(); - LuminaDbContext dbContext = _fixture.Create(); - - // Act - UnitOfWork unitOfWork = new(repositoryFactory, dbContext); - - // Assert - Assert.True(unitOfWork.Repositories.Count > 0); - } - - [Fact] - public void GetRepository_WhenRepositoryNotAdded_ShouldReturnNull() - { - // Arrange - ServiceCollection services = new(); - DataAccessLayerServices.AddDataAccessLayerServices(services); - services.AddTransient(); - services.AddTransient(); - ServiceProvider serviceProvider = services.BuildServiceProvider(); - UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); - unitOfWork.ResetRepositories(); - - // Act - IBookRepository result = unitOfWork.GetRepository(); - - // Assert - Assert.Null(result); - } - - [Fact] - public void GetRepository_WhenRepositoriesAdded_ShouldReturnRepositories() - { - // Arrange - ServiceCollection services = new(); - DataAccessLayerServices.AddDataAccessLayerServices(services); - services.AddTransient(); - services.AddTransient(); - ServiceProvider serviceProvider = services.BuildServiceProvider(); - UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService(); - - // Act & Assert - Assert.NotNull(unitOfWork.GetRepository()); + Assert.NotNull(firstAccess); + Assert.Same(firstAccess, secondAccess); + Assert.EndsWith(propertyName, firstAccess.GetType().Name); } [Fact] public async Task SaveChangesAsync_WhenCalled_ShouldCallDbContextSaveChangesAsync() { // Arrange - IRepositoryFactory repositoryFactory = _fixture.Create(); LuminaDbContext dbContext = _fixture.Create(); - UnitOfWork unitOfWork = new(repositoryFactory, dbContext); + UnitOfWork unitOfWork = new(dbContext); CancellationToken cancellationToken = new(); // Act @@ -145,4 +99,28 @@ public class UnitOfWorkTests // Assert await dbContext.Received(1).SaveChangesAsync(cancellationToken); } + + [Fact] + public void UnitOfWork_WhenResolvedFromServiceProvider_ShouldExposeRepositories() + { + // Arrange + ServiceCollection services = new(); + DataAccessLayerServices.AddDataAccessLayerServices(services); + services.AddTransient(); + services.AddTransient(); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Act + IUnitOfWork unitOfWork = serviceProvider.GetRequiredService(); + + // Assert + Assert.NotNull(unitOfWork.PermissionRepository); + Assert.NotNull(unitOfWork.RoleRepository); + Assert.NotNull(unitOfWork.UserRepository); + } + + private UnitOfWork CreateUnitOfWork() + { + return new(_fixture.Create()); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs index 33278568..c7205cd1 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs @@ -41,7 +41,7 @@ public class AuthorizationServiceTests _mockUserRepository = Substitute.For(); _mockAuthorizationPolicyFactory = Substitute.For(); - _mockUnitOfWork.GetRepository().Returns(_mockUserRepository); + _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); _sut = new AuthorizationService(_mockUnitOfWork, _mockAuthorizationPolicyFactory); }