Merge pull request #145 from BinaryAlley/refactor/replace-repository-reflection-based-instantiation

Replaces reflection-based repository instantiation with unit of work property accessors
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-08-14 09:18:51 -07:00
commit 8f3304d231
87 files changed
+541 -735

No files matched your search

@@ -31,7 +31,7 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD
{
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
ILibraryRepository libraryRepository = unitOfWork.LibraryRepository;
// execution logic
}
}
@@ -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
{
/// <summary>
/// Exposes a repository of type <typeparamref name="TRepository"/> to the Business Layer.
/// Gets the permission repository.
/// </summary>
/// <typeparam name="TRepository">The type of the exposed repository.</typeparam>
/// <returns>A repository of type <typeparamref name="TRepository"/>.</returns>
TRepository GetRepository<TRepository>();
IPermissionRepository PermissionRepository { get; }
/// <summary>
/// Gets the role permission repository.
/// </summary>
IRolePermissionRepository RolePermissionRepository { get; }
/// <summary>
/// Gets the role repository.
/// </summary>
IRoleRepository RoleRepository { get; }
/// <summary>
/// Gets the role user repository.
/// </summary>
IUserRoleRepository UserRoleRepository { get; }
/// <summary>
/// Gets the book repository.
/// </summary>
IBookRepository BookRepository { get; }
/// <summary>
/// Gets the directory scan fingerprint repository.
/// </summary>
IDirectoryScanFingerprintRepository DirectoryScanFingerprintRepository { get; }
/// <summary>
/// Gets the library repository.
/// </summary>
ILibraryRepository LibraryRepository { get; }
/// <summary>
/// Gets the library scan repository.
/// </summary>
ILibraryScanRepository LibraryScanRepository { get; }
/// <summary>
/// Gets the library scan snapshot repository.
/// </summary>
ILibraryScanSnapshotRepository LibraryScanSnapshotRepository { get; }
/// <summary>
/// Gets the library scan staging results repository.
/// </summary>
ILibraryScanStagingResultsRepository LibraryScanStagingResultsRepository { get; }
/// <summary>
/// Gets the library metadata provider configuration repository.
/// </summary>
ILibraryMetadataProviderConfigurationRepository LibraryMetadataProviderConfigurationRepository { get; }
/// <summary>
/// Gets the plugin repository.
/// </summary>
IPluginRepository PluginRepository { get; }
/// <summary>
/// Gets the user repository.
/// </summary>
IUserRepository UserRepository { get; }
/// <summary>
/// Saves all changes made to the database.
@@ -24,12 +87,24 @@ public interface IUnitOfWork
Task SaveChangesAsync(CancellationToken cancellationToken);
/// <summary>
/// Opens a transaction.
/// Begins a new database transaction.
/// </summary>
void OpenTransaction();
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task representing the asynchronous operation.</returns>
Task BeginTransactionAsync(CancellationToken cancellationToken);
/// <summary>
/// Commits a transaction.
/// Commits the current transaction.
/// </summary>
void CommitTransaction();
}
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task representing the asynchronous operation.</returns>
Task CommitTransactionAsync(CancellationToken cancellationToken);
/// <summary>
/// Rolls back the current transaction.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task representing the asynchronous operation.</returns>
Task RollbackTransactionAsync(CancellationToken cancellationToken);
}
@@ -22,8 +22,8 @@ namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPer
public class GetPermissionsQueryHandler : IQueryHandler<GetPermissionsQuery, Result<IEnumerable<PermissionResponse>>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly IPermissionRepository _permissionRepository;
/// <summary>
/// Initializes a new instance of the <see cref="GetPermissionsQueryHandler"/> class.
@@ -35,7 +35,7 @@ public class GetPermissionsQueryHandler : IQueryHandler<GetPermissionsQuery, Res
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_permissionRepository = unitOfWork.GetRepository<IPermissionRepository>();
_unitOfWork = unitOfWork;
}
/// <summary>
@@ -52,7 +52,7 @@ public class GetPermissionsQueryHandler : IQueryHandler<GetPermissionsQuery, Res
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
Result<IEnumerable<PermissionEntity>> getPermissionsResult = await _permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
Result<IEnumerable<PermissionEntity>> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
return getPermissionsResult.Match(value => Result.From(value.ToResponses()), errors => errors);
}
}
@@ -62,8 +62,6 @@ public class AddRoleCommandHandler : ICommandHandler<AddRoleCommand, Result<Role
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
// create the new role, with its permissions
RoleEntity newRole = new()
{
@@ -77,12 +75,12 @@ public class AddRoleCommandHandler : ICommandHandler<AddRoleCommand, Result<Role
})]
};
// save the new role in the repository
Result<Created> insertRoleResult = await roleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false);
Result<Created> 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<RoleEntity?> getRoleResult = await roleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false);
Result<RoleEntity?> getRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false);
if (getRoleResult.IsFailure)
return getRoleResult.Errors;
if (getRoleResult.Value is null)
@@ -62,8 +62,7 @@ public class DeleteRoleCommandHandler : ICommandHandler<DeleteRoleCommand, Resul
return Errors.Authorization.NotAuthorized;
// check if a role with the requested Id exists
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
Result<RoleEntity?> getExistingRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
Result<RoleEntity?> 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<DeleteRoleCommand, Resul
else if (getExistingRoleResult.Value.RoleName == "Admin")
return Errors.Authorization.AdminRoleCannotBeDeleted;
// delete the role and its permissions
Result<Deleted> deleteRoleResult = await roleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
Result<Deleted> deleteRoleResult = await _unitOfWork.RoleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
if (deleteRoleResult.IsFailure)
return deleteRoleResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -62,8 +62,6 @@ public class UpdateRoleCommandHandler : ICommandHandler<UpdateRoleCommand, Resul
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
// update the role and its permissions
RoleEntity newRole = new()
{
@@ -78,12 +76,12 @@ public class UpdateRoleCommandHandler : ICommandHandler<UpdateRoleCommand, Resul
}).ToList()
};
// save the updated role in the repository
Result<Updated> updateRoleResult = await roleRepository.UpdateAsync(newRole, cancellationToken).ConfigureAwait(false);
Result<Updated> 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<RoleEntity?> getRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
Result<RoleEntity?> getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
if (getRoleResult.IsFailure)
return getRoleResult.Errors;
if (getRoleResult.Value is null)
@@ -38,7 +38,7 @@ public class GetRolePermissionsQueryHandler : IQueryHandler<GetRolePermissionsQu
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_roleRepository = unitOfWork.GetRepository<IRoleRepository>();
_roleRepository = unitOfWork.RoleRepository;
_validator = validator;
}
@@ -35,7 +35,7 @@ public class GetRolesQueryHandler : IQueryHandler<GetRolesQuery, Result<IEnumera
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_roleRepository = unitOfWork.GetRepository<IRoleRepository>();
_roleRepository = unitOfWork.RoleRepository;
}
/// <summary>
@@ -80,8 +80,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
return validationResult;
// check if any users already exists (admin account is only set once!)
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
Result<IEnumerable<UserEntity>> selectUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
Result<IEnumerable<UserEntity>> 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<SetupApplicationCo
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
// insert the user
Result<Created> insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
Result<Created> insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
if (insertUserResult.IsFailure)
return insertUserResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -38,9 +38,8 @@ public class CheckInitializationQueryHandler : IQueryHandler<CheckInitialization
/// </returns>
public async Task<InitializationResponse> HandleAsync(CheckInitializationQuery query, CancellationToken cancellationToken)
{
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
// if the repository reports an error, or there are no users, the application has not been initialized
Result<IEnumerable<UserEntity>> selectUsersResult = await userRepository.GetAllAsync(cancellationToken);
Result<IEnumerable<UserEntity>> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken);
if (!selectUsersResult.IsFailure)
return new InitializationResponse(selectUsersResult.Value.Any());
return new InitializationResponse(false);
@@ -116,18 +116,16 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
if (createLibraryResult.IsFailure)
return createLibraryResult.Errors;
// get a library repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
// convert the domain library entity to a repository library entity
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
// insert the repository entity and save changes
Result<Created> insertLibraryResult = await libraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
Result<Created> 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<LibraryEntity?> getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
if (getCreatedLibraryResult.IsFailure)
return getCreatedLibraryResult.Errors;
if (getCreatedLibraryResult.Value is null)
@@ -56,10 +56,8 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibraries
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken)
{
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
// get the running library scans of the current user from the repository
Result<IEnumerable<LibraryScanEntity>> getRunningLibraryScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
Result<IEnumerable<LibraryScanEntity>> getRunningLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
if (getRunningLibraryScansResult.IsFailure)
return getRunningLibraryScansResult.Errors;
@@ -88,7 +86,7 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibraries
return cancelScanResult.Errors;
// update the status of the library scan in the repository
Result<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateLibraryScanResult.IsFailure)
return updateLibraryScanResult.Errors;
@@ -65,10 +65,8 @@ public class CancelLibraryScanCommandHandler : ICommandHandler<CancelLibraryScan
if (validationResult.Count > 0)
return validationResult;
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
// get the library scan from the repository
Result<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false);
Result<LibraryScanEntity?> 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<CancelLibraryScan
return cancelScanResult.Errors;
// update the status of the library scan in the repository
Result<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateLibraryScanResult.IsFailure)
return updateLibraryScanResult.Errors;
@@ -66,8 +66,7 @@ public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand,
return validationResult;
// get the library with the specified id from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> 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<DeleteLibraryCommand,
_domainEventsQueue.Enqueue(domainEvent);
// perform the deletion
Result<Deleted> deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
Result<Deleted> deletePersistenceLibraryResult = await _unitOfWork.LibraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (deletePersistenceLibraryResult.IsFailure)
return deletePersistenceLibraryResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -59,11 +59,8 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<IEnumerable<MediaLibraryScanResponse>>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken)
{
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
// get all media libraries that are enabled and unlocked from the persistence medium
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await libraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false);
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false);
if (getLibrariesResult.IsFailure)
return getLibrariesResult.Errors;
@@ -85,7 +82,7 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
// get the past month's scans for this library
Result<IEnumerable<LibraryScanEntity>> 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<ScanLibrariesCommand,
continue;
// add the library scan to the persistence medium
Result<Created> insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
Result<Created> insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (insertLibraryScanResult.IsFailure)
return insertLibraryScanResult.Errors;
@@ -71,11 +71,8 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
if (validationResult.Count > 0)
return validationResult;
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
// get the media library from the persistence medium
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
@@ -100,7 +97,7 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
return domainLibraryResult.Errors;
// get the past month's scans for this library
Result<IEnumerable<LibraryScanEntity>> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
Result<IEnumerable<LibraryScanEntity>> pastLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (pastLibraryScansResult.IsFailure)
return pastLibraryScansResult.Errors;
@@ -124,7 +121,7 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
return queueScanResult.Errors;
// add the library scan to the persistence medium
Result<Created> insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
Result<Created> insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (insertLibraryScanResult.IsFailure)
return insertLibraryScanResult.Errors;
@@ -97,8 +97,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
}
// get a library repository and retrieve the library to update
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> 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<UpdateLibraryCommand,
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
// update the repository entity and save changes
Result<Updated> updateLibraryResult = await libraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
Result<Updated> 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<LibraryEntity?> getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
if (getCreatedLibraryResult.IsFailure)
return getCreatedLibraryResult.Errors;
if (getCreatedLibraryResult.Value is null)
@@ -66,8 +66,7 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
throw new EventualConsistencyException(saveCoverImageResult.FirstError, saveCoverImageResult.Errors);
domainEvent.Library.SetInternalLibraryCoverImagePath(saveCoverImageResult.Value);
// update the media library with the new cover location
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
Result<Updated> updateLibraryResult = await libraryRepository.UpdateAsync(domainEvent.Library.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
Result<Updated> updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(domainEvent.Library.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateLibraryResult.IsFailure)
throw new EventualConsistencyException(updateLibraryResult.FirstError, updateLibraryResult.Errors);
@@ -28,7 +28,6 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
private readonly ILibraryScanRepository _libraryScanRepository;
private readonly IUnitOfWork _unitOfWork;
/// <summary>
@@ -47,7 +46,6 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
_mediaLibraryScanningService = mediaLibraryScanningService;
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
_libraryScanRepository = unitOfWork.GetRepository<ILibraryScanRepository>();
_unitOfWork = unitOfWork;
}
@@ -59,7 +57,7 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<Librar
public async ValueTask HandleAsync(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken)
{
// get the library scan from the repository
Result<LibraryScanEntity?> getLibraryScansResult = await _libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
Result<LibraryScanEntity?> 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<Librar
throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors);
// release the scan processing resources
ILibraryScanStagingResultsRepository stagingResultsRepository = _unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, UserId.Create(getLibraryScansResult.Value.UserId));
_mediaLibrariesScanCancellationTracker.RemoveScan(compositeId);
_mediaLibrariesScanProgressTracker.RemoveScanProgress(compositeId);
Result<Success> clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
Result<Success> clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
if (clearStagingResult.IsFailure)
throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors);
}
@@ -54,11 +54,8 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandler<LibrarySc
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken)
{
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
ILibraryScanStagingResultsRepository stagingResultsRepository = _unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
// get the library scan from the repository
Result<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(
Result<LibraryScanEntity?> 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<LibrarySc
if (!failScanResult.IsFailure)
{
// update the status of the library scan in the repository
Result<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
Result<Updated> 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<LibrarySc
// release the scan processing resources, regardless of whether the scan was already marked as failed by a concurrent job
_mediaLibrariesScanCancellationTracker.RemoveScan(domainEvent.MediaLibraryScanCompositeId);
_mediaLibrariesScanProgressTracker.RemoveScanProgress(domainEvent.MediaLibraryScanCompositeId);
Result<Success> clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
Result<Success> clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
if (clearStagingResult.IsFailure)
throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors);
@@ -54,10 +54,8 @@ public class LibraryScanFinishedDomainEventHandler : IDomainEventHandler<Library
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken)
{
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
// get the library scan from the repository
Result<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(
Result<LibraryScanEntity?> 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<Library
throw new EventualConsistencyException(finishScanResult.FirstError, finishScanResult.Errors);
// update the library scan in the repository
Result<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateLibraryScanResult.IsFailure)
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
@@ -48,10 +48,8 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler<LibrarySc
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken)
{
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
// get the library scan that was queued, from the repository
Result<LibraryScanEntity?> getLibraryScanResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
Result<LibraryScanEntity?> 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);
@@ -35,10 +35,8 @@ public class LibraryScanStartedDomainEventHandler : IDomainEventHandler<LibraryS
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken)
{
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
// update the status of the library scan in the repository
Result<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
Result<Updated> updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateLibraryScanResult.IsFailure)
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
@@ -52,8 +52,7 @@ public class GetEnabledLibrariesQueryHandler : IQueryHandler<GetEnabledLibraries
public async Task<Result<LibraryResponse[]>> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken)
{
// get the enabled libraries from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
Result<IEnumerable<LibraryEntity>> getEnabledLibrariesResult = await libraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false);
Result<IEnumerable<LibraryEntity>> getEnabledLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false);
if (getEnabledLibrariesResult.IsFailure)
return getEnabledLibrariesResult.Errors;
@@ -52,8 +52,7 @@ public class GetLibrariesQueryHandler : IQueryHandler<GetLibrariesQuery, Result<
public async Task<Result<LibraryResponse[]>> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken)
{
// get the libraries from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await libraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getLibrariesResult.IsFailure)
return getLibrariesResult.Errors;
@@ -63,8 +63,7 @@ public class GetLibraryQueryHandler : IQueryHandler<GetLibraryQuery, Result<Libr
return validationResult;
// get the library with the specified id from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
else if (getLibraryResult.Value is null)
@@ -70,8 +70,7 @@ public class GetLibraryScanProgressQueryHandler : IQueryHandler<GetLibraryScanPr
return validationResult;
// get the library with the specified id from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
else if (getLibraryResult.Value is null)
@@ -59,8 +59,7 @@ public class GetRunningLibraryScansQueryHandler : IQueryHandler<GetRunningLibrar
public async Task<Result<IEnumerable<MediaLibraryScanProgressResponse>>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken)
{
// get the ongoing library scans from the repository
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
Result<IEnumerable<LibraryScanEntity>> getRunningScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
Result<IEnumerable<LibraryScanEntity>> getRunningScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
if (getRunningScansResult.IsFailure)
return getRunningScansResult.Errors;
@@ -171,9 +171,8 @@ public class AddBookCommandHandler : ICommandHandler<AddBookCommand, Result<Book
if (createBookResult.IsFailure)
return createBookResult.Errors;
IBookRepository bookRepository = _unitOfWork.GetRepository<IBookRepository>();
BookEntity persistenceBook = createBookResult.Value.ToRepositoryEntity();
Result<Created> insertBookResult = await bookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false);
Result<Created> insertBookResult = await _unitOfWork.BookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false);
if (insertBookResult.IsFailure)
return insertBookResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -39,10 +39,8 @@ public class GetBooksQueryHandler : IQueryHandler<GetBooksQuery, Result<IEnumera
/// </returns>
public async Task<Result<IEnumerable<BookResponse>>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken)
{
// get a books repository
IBookRepository bookRepository = _unitOfWork.GetRepository<IBookRepository>();
// get all books of the media library from the book repository
Result<IEnumerable<BookEntity>> getBooksResult = await bookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
Result<IEnumerable<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
return getBooksResult.Match(result => Result.From(getBooksResult.Value.ToResponses()), errors => errors);
}
}
@@ -47,8 +47,7 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler<Reo
if (validationResult.Count > 0)
return validationResult;
ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>();
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return getConfigurationsResult.Errors;
@@ -59,7 +58,7 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler<Reo
if (configurationsByPluginId.TryGetValue(pluginId, out LibraryMetadataProviderConfigurationEntity? configuration))
{
configuration.Rank = rank + 1;
Result<Updated> upsertResult = await configurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
Result<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return upsertResult.Errors;
}
@@ -47,8 +47,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler<S
if (validationResult.Count > 0)
return validationResult;
ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>();
Result<LibraryMetadataProviderConfigurationEntity?> getConfigurationResult = await configurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
Result<LibraryMetadataProviderConfigurationEntity?> 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<S
else
{
// compute the rank to assign to the new configuration, appending it after the existing ones
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false);
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> 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<S
};
}
Result<Updated> upsertResult = await configurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
Result<Updated> upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return upsertResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -45,9 +45,8 @@ public class UpdatePluginSettingsCommandHandler : ICommandHandler<UpdatePluginSe
if (validationResult.Count > 0)
return validationResult;
IPluginRepository pluginRepository = _unitOfWork.GetRepository<IPluginRepository>();
string? settingsJson = command.Settings is not null ? JsonSerializer.Serialize(command.Settings) : null;
Result<Updated> updateResult = await pluginRepository.UpdateSettingsAsync(command.PluginId, settingsJson, cancellationToken).ConfigureAwait(false);
Result<Updated> updateResult = await _unitOfWork.PluginRepository.UpdateSettingsAsync(command.PluginId, settingsJson, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -41,14 +41,12 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler<GetLibraryM
/// </returns>
public async Task<Result<IReadOnlyList<LibraryMetadataProviderResponse>>> HandleAsync(GetLibraryMetadataProvidersQuery query, CancellationToken cancellationToken)
{
ILibraryMetadataProviderConfigurationRepository configurationRepository = _unitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>();
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> 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<IPluginRepository>();
Result<IEnumerable<PluginEntity>> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
Result<IEnumerable<PluginEntity>> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getPluginsResult.IsFailure)
return getPluginsResult.Errors;
Dictionary<Guid, string> pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name);
@@ -46,8 +46,7 @@ public class GetPluginSettingsQueryHandler : IQueryHandler<GetPluginSettingsQuer
/// </returns>
public async Task<Result<PluginSettingsResponse>> HandleAsync(GetPluginSettingsQuery query, CancellationToken cancellationToken)
{
IPluginRepository pluginRepository = _unitOfWork.GetRepository<IPluginRepository>();
Result<PluginEntity?> getPluginResult = await pluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false);
Result<PluginEntity?> getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false);
if (getPluginResult.IsFailure)
return getPluginResult.Errors;
PluginEntity? pluginEntity = getPluginResult.Value;
@@ -40,10 +40,7 @@ public class GetPluginsQueryHandler : IQueryHandler<GetPluginsQuery, Result<IRea
/// </returns>
public async Task<Result<IReadOnlyList<PluginResponse>>> HandleAsync(GetPluginsQuery query, CancellationToken cancellationToken)
{
IPluginRepository pluginRepository = _unitOfWork.GetRepository<IPluginRepository>();
Result<IEnumerable<PluginEntity>> getPluginsResult = await pluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
return getPluginsResult.Match(
plugins => Result.From<IReadOnlyList<PluginResponse>>(plugins.Select(plugin => plugin.ToResponse()).ToList()),
errors => errors);
Result<IEnumerable<PluginEntity>> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
return getPluginsResult.Match(plugins => Result.From<IReadOnlyList<PluginResponse>>([.. plugins.Select(plugin => plugin.ToResponse())]), errors => errors);
}
}
@@ -55,8 +55,7 @@ public class ChangePasswordCommandHandler : ICommandHandler<ChangePasswordComman
if (validationResult.Count > 0)
return validationResult;
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
Result<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> 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<ChangePasswordComman
getUserResult.Value.TempPassword = null;
getUserResult.Value.TempPasswordCreated = null;
// update the user
Result<Updated> updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
Result<Updated> updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
if (updateUserResult.IsFailure)
return updateUserResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -65,8 +65,7 @@ public class RecoverPasswordCommandHandler : ICommandHandler<RecoverPasswordComm
return validationResult;
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
Result<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> 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<RecoverPasswordComm
getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator
getUserResult.Value.TempPasswordCreated = DateTime.UtcNow;
// update the user
Result<Updated> updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
Result<Updated> updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
if (updateUserResult.IsFailure)
return updateUserResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -74,8 +74,7 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
return validationResult;
// check if any users already exists (admin account is only set once!)
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
Result<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> 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<RegisterUserCommand, R
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
// insert the user
Result<Created> insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
Result<Created> insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
if (insertUserResult.IsFailure)
return insertUserResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -22,9 +22,9 @@ namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUser
/// </summary>
public class GetUsersQueryHandler : IQueryHandler<GetUsersQuery, Result<IEnumerable<UserResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IUserRepository _userRepository;
/// <summary>
/// Initializes a new instance of the <see cref="GetUsersQueryHandler"/> class.
@@ -36,7 +36,7 @@ public class GetUsersQueryHandler : IQueryHandler<GetUsersQuery, Result<IEnumera
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_userRepository = unitOfWork.GetRepository<IUserRepository>();
_unitOfWork = unitOfWork;
}
/// <summary>
@@ -53,7 +53,7 @@ public class GetUsersQueryHandler : IQueryHandler<GetUsersQuery, Result<IEnumera
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
Result<IEnumerable<UserEntity>> getRolesResult = await _userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
Result<IEnumerable<UserEntity>> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
return getRolesResult.Match(value => Result.From(value.ToResponses()), errors => errors);
}
}
@@ -74,8 +74,7 @@ public class LoginUserQueryHandler : IQueryHandler<LoginUserQuery, Result<LoginR
return validationResult;
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
Result<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> 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<LoginUserQuery, Result<LoginR
{
getUserResult.Value.TempPassword = null;
getUserResult.Value.TempPasswordCreated = null;
await userRepository.UpdateAsync(getUserResult.Value, cancellationToken);
await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken);
await _unitOfWork.SaveChangesAsync(cancellationToken);
return Errors.Authentication.TempPasswordExpired;
}
@@ -65,13 +65,8 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
if (!isAdmin)
return ApplicationErrors.Authorization.NotAuthorized;
// get repositories
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
IPermissionRepository permissionRepository = _unitOfWork.GetRepository<IPermissionRepository>();
// get the user to update
Result<UserEntity?> getUserResult = await userRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> 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<Update
if (command.RoleId is not null)
{
// get the new role
getRoleResult = await roleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken).ConfigureAwait(false);
getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken).ConfigureAwait(false);
if (getRoleResult.IsFailure || getRoleResult.Value is null)
return ApplicationErrors.Authorization.RoleNotFound;
@@ -87,7 +82,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && getRoleResult.Value.RoleName != "Admin")
{
// count how many admins we have
Result<IEnumerable<UserEntity>> getAllUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
Result<IEnumerable<UserEntity>> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getAllUsersResult.IsFailure)
return getAllUsersResult.Errors;
@@ -98,7 +93,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
}
// get the permissions to assign
Result<IEnumerable<PermissionEntity>> 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<Update
TempPasswordCreated = userToUpdate.TempPasswordCreated,
Libraries = userToUpdate.Libraries,
UserRole = userRole,
UserPermissions = command.Permissions.Select(permissionId => 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<Updated> updateResult = await userRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false);
Result<Updated> updateResult = await _unitOfWork.UserRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
@@ -23,9 +23,9 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserP
/// </summary>
public class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQuery, Result<IEnumerable<PermissionResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IUserRepository _userRepository;
private readonly IValidator<GetUserPermissionsQuery> _validator;
/// <summary>
@@ -39,7 +39,7 @@ public class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQu
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_userRepository = unitOfWork.GetRepository<IUserRepository>();
_unitOfWork = unitOfWork;
_validator = validator;
}
@@ -62,7 +62,7 @@ public class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQu
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
// get the user from the repository and return its permissions
Result<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsFailure)
return getUserResult.Errors;
else if (getUserResult.Value is null)
@@ -22,9 +22,9 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserR
/// </summary>
public class GetUserRoleQueryHandler : IQueryHandler<GetUserRoleQuery, Result<RoleResponse?>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IUserRepository _userRepository;
private readonly IValidator<GetUserRoleQuery> _validator;
/// <summary>
@@ -38,7 +38,7 @@ public class GetUserRoleQueryHandler : IQueryHandler<GetUserRoleQuery, Result<Ro
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_userRepository = unitOfWork.GetRepository<IUserRepository>();
_unitOfWork = unitOfWork;
_validator = validator;
}
@@ -61,7 +61,7 @@ public class GetUserRoleQueryHandler : IQueryHandler<GetUserRoleQuery, Result<Ro
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
// get the user from the repository and return its roles
Result<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsFailure)
return getUserResult.Errors;
else if (getUserResult.Value is null)
@@ -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<IUnitOfWork, UnitOfWork>();
services.AddScoped<UpdateAuditableEntitiesInterceptor>();
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<Type> 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<IDataSeedService, DataSeedService>();
}
}
@@ -1,15 +0,0 @@
namespace Lumina.DataAccess.Core.Repositories.Common.Factory;
/// <summary>
/// Interface for the repositories factory.
/// </summary>
public interface IRepositoryFactory
{
/// <summary>
/// Creates a new repository of type <typeparamref name="TRepository"/>.
/// </summary>
/// <typeparam name="TRepository">The type of repository to create.</typeparam>
/// <returns>A repository of type <typeparamref name="TRepository"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the type of the requested repository has not been registered.</exception>
TRepository CreateRepository<TRepository>() where TRepository : notnull;
}
@@ -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;
/// <summary>
/// Custom collection for storing repositories.
/// </summary>
public class RepositoryDictionary
{
private readonly List<KeyValuePair<Type, object>> _container = [];
/// <summary>
/// Gets the number of added repositories.
/// </summary>
public int Count => _container.Count;
/// <summary>
/// Resets the collection of repositories.
/// </summary>
public void Clear()
{
_container.Clear();
}
/// <summary>
/// Adds a repository of type <typeparamref name="TParam"/> to the collection.
/// </summary>
/// <typeparam name="TParam">The type of the repository to add to the collection.</typeparam>
/// <param name="value">The repository to add.</param>
public void Add<TParam>(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<Type, object>(value.GetType(), value));
else
throw new ArgumentException("Value must implement IRepository interface!");
}
/// <summary>
/// Gets a repository of type <typeparamref name="TResult"/> from the collection.
/// </summary>
/// <typeparam name="TResult">The type of the repository interface to get from the collection.</typeparam>
/// <param name="key">The concrete type of the repository interface to get.</param>
/// <returns>A repository implementing <typeparamref name="TResult"/>.</returns>
public TResult Get<TResult>(Type key)
{
return (TResult)_container.FirstOrDefault(e => e.Key == key).Value;
}
}
@@ -1,34 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.Extensions.DependencyInjection;
using System;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Common.Factory;
/// <summary>
/// Concrete implementation for the repositories factory.
/// </summary>
public class RepositoryFactory : IRepositoryFactory
{
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="RepositoryFactory"/> class.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
public RepositoryFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
/// <summary>
/// Creates a new repository of type <typeparamref name="TRepository"/>.
/// </summary>
/// <typeparam name="TRepository">The type of repository to create.</typeparam>
/// <returns>A repository of type <typeparamref name="TRepository"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the type of the requested repository has not been registered.</exception>
public TRepository CreateRepository<TRepository>() where TRepository : notnull
{
return _serviceProvider.GetRequiredService<TRepository>() ?? throw new ArgumentException();
}
}
@@ -44,7 +44,6 @@ public class DataSeedService : IDataSeedService
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken)
{
IPermissionRepository permissionRepository = _unitOfWork.GetRepository<IPermissionRepository>();
// 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<Created> insertPermissionResult = await permissionRepository.InsertAsync(permission, cancellationToken).ConfigureAwait(false);
Result<Created> insertPermissionResult = await _unitOfWork.PermissionRepository.InsertAsync(permission, cancellationToken).ConfigureAwait(false);
if (insertPermissionResult.IsFailure)
return insertPermissionResult.Errors;
}
@@ -71,8 +70,6 @@ public class DataSeedService : IDataSeedService
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken)
{
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
// 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<Created> insertRoleResult = await roleRepository.InsertAsync(role, cancellationToken).ConfigureAwait(false);
Result<Created> insertRoleResult = await _unitOfWork.RoleRepository.InsertAsync(role, cancellationToken).ConfigureAwait(false);
if (insertRoleResult.IsFailure)
return insertRoleResult.Errors;
}
@@ -96,12 +93,8 @@ public class DataSeedService : IDataSeedService
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken)
{
IRolePermissionRepository rolePermissionRepository = _unitOfWork.GetRepository<IRolePermissionRepository>();
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
IPermissionRepository permissionRepository = _unitOfWork.GetRepository<IPermissionRepository>();
// get the admin role
Result<RoleEntity?> getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false);
Result<RoleEntity?> 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<IEnumerable<PermissionEntity>> getPermissionsResult = await permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
Result<IEnumerable<PermissionEntity>> 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<Created> insertRolePermissionResult = await rolePermissionRepository.InsertAsync(rolePermissionEntity, cancellationToken).ConfigureAwait(false);
Result<Created> insertRolePermissionResult = await _unitOfWork.RolePermissionRepository.InsertAsync(rolePermissionEntity, cancellationToken).ConfigureAwait(false);
if (insertRolePermissionResult.IsFailure)
return insertRolePermissionResult.Errors;
}
@@ -141,13 +134,8 @@ public class DataSeedService : IDataSeedService
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken)
{
IUserRoleRepository userRoleRepository = _unitOfWork.GetRepository<IUserRoleRepository>();
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
// get the admin role
Result<RoleEntity?> getAdminRoleResult = await roleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false);
Result<RoleEntity?> 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<UserEntity?> getUserResult = await userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> 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<Created> insertUserRoleResult = await userRoleRepository.InsertAsync(userRole, cancellationToken).ConfigureAwait(false);
Result<Created> insertUserRoleResult = await _unitOfWork.UserRoleRepository.InsertAsync(userRole, cancellationToken).ConfigureAwait(false);
if (insertUserRoleResult.IsFailure)
return insertUserRoleResult.Errors;
+214 -66
View File
@@ -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;
/// <summary>
/// Interaction boundary with the Data Access Layer.
/// </summary>
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;
/// <summary>
/// Gets or sets the collection of available repositories.
/// Gets the permission repository.
/// </summary>
internal RepositoryDictionary Repositories { get; private set; } = new RepositoryDictionary();
/// <summary>
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
/// </summary>
/// <param name="repositoryFactory">The factory used to generate repositories.</param>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public UnitOfWork(IRepositoryFactory repositoryFactory, LuminaDbContext luminaDbContext)
public IPermissionRepository PermissionRepository
{
_repositoryFactory = repositoryFactory;
_luminaDbContext = luminaDbContext;
AddRepositories();
}
/// <summary>
/// Adds all the repositories from the Data Access Layer so that they can be exposed to the Business Layer.
/// </summary>
internal void AddRepositories()
{
// get all the concrete implementations of IRepository<>
IEnumerable<Type> 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;
}
}
/// <summary>
/// Exposes a repository of type <typeparamref name="TRepository"/> to the Business Logic Layer.
/// Gets the role permission repository.
/// </summary>
/// <typeparam name="TRepository">The type of the exposed repository.</typeparam>
/// <returns>A repository of type <typeparamref name="TRepository"/>.</returns>
public TRepository GetRepository<TRepository>()
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<TRepository>(repositoryType);
get
{
_rolePermissionRepository ??= new RolePermissionRepository(_luminaDbContext);
return _rolePermissionRepository;
}
}
/// <summary>
/// Resets the list of repositories.
/// Gets the role repository.
/// </summary>
internal void ResetRepositories()
public IRoleRepository RoleRepository
{
Repositories.Clear();
get
{
_roleRepository ??= new RoleRepository(_luminaDbContext);
return _roleRepository;
}
}
/// <summary>
/// Gets the user role repository.
/// </summary>
public IUserRoleRepository UserRoleRepository
{
get
{
_userRoleRepository ??= new UserRoleRepository(_luminaDbContext);
return _userRoleRepository;
}
}
/// <summary>
/// Gets the book repository.
/// </summary>
public IBookRepository BookRepository
{
get
{
_bookRepository ??= new BookRepository(_luminaDbContext);
return _bookRepository;
}
}
/// <summary>
/// Gets the directory scan fingerprint repository.
/// </summary>
public IDirectoryScanFingerprintRepository DirectoryScanFingerprintRepository
{
get
{
_directoryScanFingerprintRepository ??= new DirectoryScanFingerprintRepository(_luminaDbContext);
return _directoryScanFingerprintRepository;
}
}
/// <summary>
/// Gets the library repository.
/// </summary>
public ILibraryRepository LibraryRepository
{
get
{
_libraryRepository ??= new LibraryRepository(_luminaDbContext);
return _libraryRepository;
}
}
/// <summary>
/// Gets the library scan repository.
/// </summary>
public ILibraryScanRepository LibraryScanRepository
{
get
{
_libraryScanRepository ??= new LibraryScanRepository(_luminaDbContext);
return _libraryScanRepository;
}
}
/// <summary>
/// Gets the library scan snapshot repository.
/// </summary>
public ILibraryScanSnapshotRepository LibraryScanSnapshotRepository
{
get
{
_libraryScanSnapshotRepository ??= new LibraryScanSnapshotRepository(_luminaDbContext);
return _libraryScanSnapshotRepository;
}
}
/// <summary>
/// Gets the library scan staging results repository.
/// </summary>
public ILibraryScanStagingResultsRepository LibraryScanStagingResultsRepository
{
get
{
_libraryScanStagingResultsRepository ??= new LibraryScanStagingResultsRepository(_luminaDbContext);
return _libraryScanStagingResultsRepository;
}
}
/// <summary>
/// Gets the library metadata provider configuration repository.
/// </summary>
public ILibraryMetadataProviderConfigurationRepository LibraryMetadataProviderConfigurationRepository
{
get
{
_libraryMetadataProviderConfigurationRepository ??= new LibraryMetadataProviderConfigurationRepository(_luminaDbContext);
return _libraryMetadataProviderConfigurationRepository;
}
}
/// <summary>
/// Gets the plugin repository.
/// </summary>
public IPluginRepository PluginRepository
{
get
{
_pluginRepository ??= new PluginRepository(_luminaDbContext);
return _pluginRepository;
}
}
/// <summary>
/// Gets the user repository.
/// </summary>
public IUserRepository UserRepository
{
get
{
_userRepository ??= new UserRepository(_luminaDbContext);
return _userRepository;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public UnitOfWork(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
@@ -100,18 +215,51 @@ public class UnitOfWork : IUnitOfWork
}
/// <summary>
/// Opens a transaction.
/// Begins a new database transaction.
/// </summary>
public void OpenTransaction()
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public async Task BeginTransactionAsync(CancellationToken cancellationToken)
{
throw new NotImplementedException();
_transaction = await _luminaDbContext.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Commits a transaction.
/// Commits the current transaction.
/// </summary>
public void CommitTransaction()
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task representing the asynchronous operation.</returns>
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;
}
}
/// <summary>
/// Rolls back the current transaction.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public async Task RollbackTransactionAsync(CancellationToken cancellationToken)
{
if (_transaction is not null)
{
await _transaction.RollbackAsync(cancellationToken).ConfigureAwait(false);
await _transaction.DisposeAsync().ConfigureAwait(false);
_transaction = null;
}
}
/// <summary>
/// Disposes the unit of work and its resources.
/// </summary>
public void Dispose()
{
_transaction?.Dispose();
_luminaDbContext.Dispose();
}
}
@@ -23,7 +23,7 @@ namespace Lumina.Infrastructure.Core.Authorization;
/// </summary>
public class AuthorizationService : IAuthorizationService
{
private readonly IUserRepository _userRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationPolicyFactory _authorizationPolicyFactory;
/// <summary>
@@ -33,7 +33,7 @@ public class AuthorizationService : IAuthorizationService
/// <param name="authorizationPolicyFactory">The factory used to generate authorization policies.</param>
public AuthorizationService(IUnitOfWork unitOfWork, IAuthorizationPolicyFactory authorizationPolicyFactory)
{
_userRepository = unitOfWork.GetRepository<IUserRepository>();
_unitOfWork = unitOfWork;
_authorizationPolicyFactory = authorizationPolicyFactory;
}
@@ -46,7 +46,7 @@ public class AuthorizationService : IAuthorizationService
/// <returns><see langword="true"/> if the user has the specified permission, <see langword="false"/> otherwise.</returns>
public async Task<bool> HasPermissionAsync(Guid userId, AuthorizationPermission permission, CancellationToken cancellationToken)
{
Result<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> 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
/// <returns><see langword="true"/> if the user is in the specified role, <see langword="false"/> otherwise.</returns>
public async Task<bool> IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken)
{
Result<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> 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
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="UserAuthorizationEntity"/>, or an error.</returns>
public async Task<Result<UserAuthorizationEntity>> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken)
{
Result<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> 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<AuthorizationPermission> directPermissions = getUserResult.Value.UserPermissions
.Select(userPermission => userPermission.Permission.PermissionName)
.ToHashSet();
HashSet<AuthorizationPermission> directPermissions = [.. getUserResult.Value.UserPermissions.Select(userPermission => userPermission.Permission.PermissionName)];
// get permissions from roles
HashSet<AuthorizationPermission>? rolePermissions = getUserResult.Value.UserRole?.Role.RolePermissions
@@ -17,7 +17,7 @@ namespace Lumina.Infrastructure.Core.Authorization.Policies.Over18;
/// </summary>
public class Over18Policy : IOver18Policy
{
private readonly IUserRepository _userRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly IDateTimeProvider _dateTimeProvider;
/// <summary>
@@ -27,7 +27,7 @@ public class Over18Policy : IOver18Policy
/// <param name="dateTimeProvider">Injected service for time related functionality.</param>
public Over18Policy(IUnitOfWork unitOfWork, IDateTimeProvider dateTimeProvider)
{
_userRepository = unitOfWork.GetRepository<IUserRepository>();
_unitOfWork = unitOfWork;
_dateTimeProvider = dateTimeProvider;
}
@@ -39,7 +39,7 @@ public class Over18Policy : IOver18Policy
/// <returns><see langword="true"/> if the policy evaluation succeeds, <see langword="false"/> otherwise.</returns>
public async Task<bool> EvaluateAsync(Guid userId, CancellationToken cancellationToken)
{
Result<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
if (getUserResult.IsFailure || getUserResult.Value is null)
return false;
@@ -59,7 +59,7 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
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<Updated> markChangesResult = await stagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false);
Result<Updated> markChangesResult = await unitOfWork.LibraryScanStagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (markChangesResult.IsFailure)
throw new InvalidOperationException(markChangesResult.FirstError.Description);
@@ -63,13 +63,13 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// count the files that need hashing, for progress reporting purposes
Result<int> getFilesToHashCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
Result<int> 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<IReadOnlyList<HashedFileSystemFileDto>> getFilesToHashPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
Result<IReadOnlyList<HashedFileSystemFileDto>> getFilesToHashPageResult = await unitOfWork.LibraryScanStagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
if (getFilesToHashPageResult.IsFailure)
throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description);
IReadOnlyList<HashedFileSystemFileDto> 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<Updated> updateHashesResult = await stagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
Result<Updated> updateHashesResult = await unitOfWork.LibraryScanStagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
if (updateHashesResult.IsFailure)
throw new InvalidOperationException(updateHashesResult.FirstError.Description);
@@ -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<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
ILibraryMetadataProviderConfigurationRepository configurationRepository = unitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>();
IBookRepository bookRepository = unitOfWork.GetRepository<IBookRepository>();
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<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
List<IRemoteMetadataProvider> providers = [];
@@ -96,7 +93,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
}
// count the books that need their metadata enriched, for progress reporting purposes
Result<int> getBooksToEnrichCountResult = await bookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
Result<int> 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<IReadOnlyList<BookEntity>> getBooksPageResult = await bookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
Result<IReadOnlyList<BookEntity>> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
if (getBooksPageResult.IsFailure)
throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
IReadOnlyList<BookEntity> 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;
@@ -66,7 +66,7 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
ILibraryScanSnapshotRepository libraryScanSnapshotRepository = unitOfWork.GetRepository<ILibraryScanSnapshotRepository>();
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<IReadOnlyList<string>> getDeletedPathsResult = await libraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
Result<IReadOnlyList<string>> 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<Updated> applySnapshotSwapResult = await libraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
Result<Updated> 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<IReadOnlyList<string>> getPathsResult = await libraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
Result<IReadOnlyList<string>> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getPathsResult.IsFailure)
throw new InvalidOperationException(getPathsResult.FirstError.Description);
IBookRepository bookRepository = unitOfWork.GetRepository<IBookRepository>();
foreach (string path in getPathsResult.Value)
{
cancellationToken.ThrowIfCancellationRequested();
Result<BookEntity?> getExistingBookResult = await bookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false);
Result<BookEntity?> 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<Created> insertBookResult = await bookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false);
Result<Created> insertBookResult = await unitOfWork.BookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false);
if (insertBookResult.IsFailure)
throw new InvalidOperationException(insertBookResult.FirstError.Description);
}
@@ -79,14 +79,11 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>()!;
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
IDirectoryScanFingerprintRepository directoryScanFingerprintRepository = unitOfWork.GetRepository<IDirectoryScanFingerprintRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the library from the repository
Result<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> 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<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
{
Result<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await directoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
Result<Dictionary<string, DirectoryScanFingerprintEntity>> 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<Created> insertResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
Result<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
if (insertResult.IsFailure)
throw new InvalidOperationException(insertResult.FirstError.Description);
}
if (fingerprintBatch.Count > 0)
{
Result<Updated> upsertResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
Result<Updated> upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
throw new InvalidOperationException(upsertResult.FirstError.Description);
}
@@ -50,7 +50,6 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
IPluginRepository pluginRepository = unitOfWork.GetRepository<IPluginRepository>();
foreach (IPlugin plugin in _pluginManager.GetPlugins())
{
@@ -66,7 +65,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
CreatedBy = default,
UpdatedBy = default
};
Result<Updated> upsertResult = await pluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
Result<Updated> 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);
}
@@ -36,8 +36,7 @@ internal sealed class PluginSettingsStore : IPluginSettingsStore
/// <inheritdoc/>
public async Task<IReadOnlyDictionary<string, string>?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken)
{
IPluginRepository pluginRepository = _unitOfWork.GetRepository<IPluginRepository>();
Result<PluginEntity?> getPluginResult = await pluginRepository.GetByIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
Result<PluginEntity?> 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);
@@ -45,7 +45,7 @@ public class GetPermissionsQueryHandlerTests
_userId = Guid.NewGuid();
_mockCurrentUserService.UserId.Returns(_userId);
_mockUnitOfWork.GetRepository<IPermissionRepository>().Returns(_mockPermissionRepository);
_mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository);
_sut = new GetPermissionsQueryHandler(
_mockAuthorizationService,
@@ -51,7 +51,7 @@ public class AddRoleCommandHandlerTests
_userId = Guid.NewGuid();
_mockCurrentUserService.UserId.Returns(_userId);
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(_mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
_sut = new AddRoleCommandHandler(
_mockAuthorizationService,
@@ -48,7 +48,7 @@ public class DeleteRoleCommandHandlerTests
_userId = Guid.NewGuid();
_mockCurrentUserService.UserId.Returns(_userId);
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(_mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
_sut = new DeleteRoleCommandHandler(
_mockAuthorizationService,
@@ -51,7 +51,7 @@ public class UpdateRoleCommandHandlerTests
_userId = Guid.NewGuid();
_mockCurrentUserService.UserId.Returns(_userId);
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(_mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
_sut = new UpdateRoleCommandHandler(
_mockAuthorizationService,
@@ -50,7 +50,7 @@ public class GetRolePermissionsQueryHandlerTests
_userId = Guid.NewGuid();
_mockCurrentUserService.UserId.Returns(_userId);
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(_mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
_sut = new GetRolePermissionsQueryHandler(
_mockAuthorizationService,
@@ -46,7 +46,7 @@ public class GetRolesQueryHandlerTests
_userId = Guid.NewGuid();
_mockCurrentUserService.UserId.Returns(_userId);
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(_mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
_sut = new GetRolesQueryHandler(
_mockAuthorizationService,
@@ -58,7 +58,7 @@ public class SetupApplicationCommandHandlerTests
mockValidator.Validate(Arg.Any<SetupApplicationCommand>())
.Returns([]);
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
_sut = new SetupApplicationCommandHandler(
@@ -34,7 +34,7 @@ public class CheckInitializationQueryHandlerTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_sut = new CheckInitializationQueryHandler(_mockUnitOfWork);
}
@@ -47,7 +47,7 @@ public class AddBookCommandHandlerTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockUnitOfWork.GetRepository<IBookRepository>().Returns(_mockBookRepository);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
IValidator<AddBookCommand> mockValidator = Substitute.For<IValidator<AddBookCommand>>();
mockValidator.Validate(Arg.Any<AddBookCommand>())
@@ -31,7 +31,7 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockUnitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>().Returns(_mockConfigurationRepository);
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
IValidator<ReorderLibraryMetadataProvidersCommand> mockValidator = Substitute.For<IValidator<ReorderLibraryMetadataProvidersCommand>>();
mockValidator.Validate(Arg.Any<ReorderLibraryMetadataProvidersCommand>())
.Returns([]);
@@ -30,7 +30,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockUnitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>().Returns(_mockConfigurationRepository);
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
IValidator<SetLibraryMetadataProviderEnabledCommand> mockValidator = Substitute.For<IValidator<SetLibraryMetadataProviderEnabledCommand>>();
mockValidator.Validate(Arg.Any<SetLibraryMetadataProviderEnabledCommand>())
.Returns([]);
@@ -29,7 +29,7 @@ public class UpdatePluginSettingsCommandHandlerTests
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.GetRepository<IPluginRepository>().Returns(_mockPluginRepository);
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
IValidator<UpdatePluginSettingsCommand> mockValidator = Substitute.For<IValidator<UpdatePluginSettingsCommand>>();
mockValidator.Validate(Arg.Any<UpdatePluginSettingsCommand>())
.Returns([]);
@@ -30,7 +30,7 @@ public class GetPluginsQueryHandlerTests
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.GetRepository<IPluginRepository>().Returns(_mockPluginRepository);
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
_sut = new GetPluginsQueryHandler(_mockUnitOfWork);
}
@@ -38,7 +38,7 @@ public class ChangePasswordCommandHandlerTests
_mockHashService = Substitute.For<IPasswordHashService>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
IValidator<ChangePasswordCommand> mockValidator = Substitute.For<IValidator<ChangePasswordCommand>>();
mockValidator.Validate(Arg.Any<ChangePasswordCommand>())
@@ -43,7 +43,7 @@ public class RecoverPasswordCommandHandlerTests
_mockCryptographyService = Substitute.For<ICryptographyService>();
_mockUserRepository = Substitute.For<IUserRepository>();
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
IValidator<RecoverPasswordCommand> mockValidator = Substitute.For<IValidator<RecoverPasswordCommand>>();
mockValidator.Validate(Arg.Any<RecoverPasswordCommand>())
@@ -49,7 +49,7 @@ public class RegisterUserCommandHandlerTests
_mockUserRepository = Substitute.For<IUserRepository>();
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
IValidator<RegisterUserCommand> mockValidator = Substitute.For<IValidator<RegisterUserCommand>>();
@@ -48,7 +48,7 @@ public class GetUsersQueryHandlerTests
_userId = Guid.NewGuid();
_mockCurrentUserService.UserId.Returns(_userId);
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_sut = new GetUsersQueryHandler(
_mockAuthorizationService,
@@ -48,7 +48,7 @@ public class LoginUserQueryHandlerTests
_mockUserRepository = Substitute.For<IUserRepository>();
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
IValidator<LoginUserQuery> mockValidator = Substitute.For<IValidator<LoginUserQuery>>();
@@ -57,9 +57,9 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
_userId = Guid.NewGuid();
_mockCurrentUserService.UserId.Returns(_userId);
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(_mockRoleRepository);
_mockUnitOfWork.GetRepository<IPermissionRepository>().Returns(_mockPermissionRepository);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
_mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository);
IValidator<UpdateUserRoleAndPermissionsCommand> mockValidator = Substitute.For<IValidator<UpdateUserRoleAndPermissionsCommand>>();
mockValidator.Validate(Arg.Any<UpdateUserRoleAndPermissionsCommand>())
@@ -49,7 +49,7 @@ public class GetUserPermissionsQueryHandlerTests
_userId = Guid.NewGuid();
_mockCurrentUserService.UserId.Returns(_userId);
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
IValidator<GetUserPermissionsQuery> mockValidator = Substitute.For<IValidator<GetUserPermissionsQuery>>();
mockValidator.Validate(Arg.Any<GetUserPermissionsQuery>())
@@ -47,7 +47,7 @@ public class GetUserRoleQueryHandlerTests
_userId = Guid.NewGuid();
_mockCurrentUserService.UserId.Returns(_userId);
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
IValidator<GetUserRoleQuery> mockValidator = Substitute.For<IValidator<GetUserRoleQuery>>();
mockValidator.Validate(Arg.Any<GetUserRoleQuery>())
@@ -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<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert
IBookRepository? repository = serviceProvider.GetService<IBookRepository>();
Assert.NotNull(repository);
IUnitOfWork unitOfWork = serviceProvider.GetRequiredService<IUnitOfWork>();
Assert.NotNull(unitOfWork.BookRepository);
Assert.NotNull(unitOfWork.PermissionRepository);
}
}
@@ -1,6 +0,0 @@
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory.Fixtures;
/// <summary>
/// Repository fixture interface for testing non registered repositories.
/// </summary>
public interface IUnregisteredRepository { }
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="RepositoryDictionary"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RepositoryDictionaryTests
{
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="RepositoryDictionaryTests"/> class.
/// </summary>
public RepositoryDictionaryTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void Add_WhenValidRepositoryItemIsAdded_ShouldIncreaseCount()
{
// Arrange
BookRepository bookRepository = _fixture.Create<BookRepository>();
RepositoryDictionary repositoryDictionary = new();
// Act
repositoryDictionary.Add<IBookRepository>(bookRepository);
// Assert
Assert.Equal(1, repositoryDictionary.Count);
}
[Fact]
public void Clear_WhenCalled_ShouldRemoveAllItems()
{
// Arrange
BookRepository bookRepository = _fixture.Create<BookRepository>();
RepositoryDictionary repositoryDictionary = new();
repositoryDictionary.Add<IBookRepository>(bookRepository);
// Act
repositoryDictionary.Clear();
// Assert
Assert.Equal(0, repositoryDictionary.Count);
}
[Fact]
public void Get_WhenRepositoryExists_ShouldReturnCorrectRepository()
{
// Arrange
BookRepository expected = _fixture.Create<BookRepository>();
RepositoryDictionary repositoryDictionary = new();
repositoryDictionary.Add<IBookRepository>(expected);
// Act
IBookRepository actual = repositoryDictionary.Get<IBookRepository>(typeof(BookRepository));
// Assert
Assert.Same(expected, actual);
}
[Fact]
public void Add_WhenNullValueIsProvided_ShouldThrowArgumentException()
{
// Arrange
RepositoryDictionary repositoryDictionary = new();
// Act & Assert
Assert.Throws<ArgumentException>(() => repositoryDictionary.Add<IBookRepository>(null!));
}
[Fact]
public void Add_WhenDuplicateValueIsAdded_ShouldThrowArgumentException()
{
// Arrange
BookRepository bookRepository = _fixture.Create<BookRepository>();
RepositoryDictionary repositoryDictionary = new();
repositoryDictionary.Add<IBookRepository>(bookRepository);
// Act & Assert
ArgumentException exception = Assert.Throws<ArgumentException>(() => repositoryDictionary.Add<IBookRepository>(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<ArgumentException>(() => repositoryDictionary.Add(nonRepository));
Assert.Equal("Value must implement IRepository interface!", exception.Message);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="RepositoryFactory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RepositoryFactoryTests
{
[Fact]
public void CreateRepository_WhenCalled_ShouldReturnCorrectRepository()
{
// Arrange
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
RepositoryFactory repositoryFactory = new(serviceProvider);
// Act
IBookRepository result = repositoryFactory.CreateRepository<IBookRepository>();
// Assert
Assert.NotNull(result);
Assert.IsAssignableFrom<IBookRepository>(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<InvalidOperationException>(
() => repositoryFactory.CreateRepository<IUnregisteredRepository>());
Assert.Equal(
"No service for type 'Lumina.DataAccess.UnitTests.Core.Repositories.Common.Factory.Fixtures.IUnregisteredRepository' has been registered.",
exception.Message);
}
}
@@ -43,7 +43,7 @@ public class DataSeedServiceTests
_fixedUtcNow = DateTime.UtcNow;
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
_mockUnitOfWork.GetRepository<IPermissionRepository>().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<IRoleRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
mockRoleRepository
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
@@ -156,7 +156,7 @@ public class DataSeedServiceTests
// Arrange
Guid userId = Guid.NewGuid();
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
Error expectedError = Error.Conflict("Role.Conflict", "Role already exists");
mockRoleRepository
@@ -181,7 +181,7 @@ public class DataSeedServiceTests
List<string> capturedRoleNames = [];
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
mockRoleRepository
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
@@ -203,7 +203,7 @@ public class DataSeedServiceTests
RoleEntity? capturedRole = null;
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
mockRoleRepository
.InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>())
@@ -238,9 +238,9 @@ public class DataSeedServiceTests
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
IRolePermissionRepository mockRolePermissionRepository = Substitute.For<IRolePermissionRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.GetRepository<IPermissionRepository>().Returns(mockPermissionRepository);
_mockUnitOfWork.GetRepository<IRolePermissionRepository>().Returns(mockRolePermissionRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
_mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository);
_mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository);
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
mockPermissionRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(permissions);
@@ -271,7 +271,7 @@ public class DataSeedServiceTests
// Arrange
Guid userId = Guid.NewGuid();
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
mockRoleRepository
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
@@ -297,8 +297,8 @@ public class DataSeedServiceTests
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.GetRepository<IPermissionRepository>().Returns(mockPermissionRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
_mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository);
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
mockPermissionRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(expectedError);
@@ -326,9 +326,9 @@ public class DataSeedServiceTests
IPermissionRepository mockPermissionRepository = Substitute.For<IPermissionRepository>();
IRolePermissionRepository mockRolePermissionRepository = Substitute.For<IRolePermissionRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.GetRepository<IPermissionRepository>().Returns(mockPermissionRepository);
_mockUnitOfWork.GetRepository<IRolePermissionRepository>().Returns(mockRolePermissionRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
_mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository);
_mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository);
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
mockPermissionRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(permissions);
@@ -352,7 +352,7 @@ public class DataSeedServiceTests
Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role");
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
mockRoleRepository
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
@@ -383,9 +383,9 @@ public class DataSeedServiceTests
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
IUserRoleRepository mockUserRoleRepository = Substitute.For<IUserRoleRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(mockUserRepository);
_mockUnitOfWork.GetRepository<IUserRoleRepository>().Returns(mockUserRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
_mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository);
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(adminUser);
@@ -417,7 +417,7 @@ public class DataSeedServiceTests
// Arrange
Guid userId = Guid.NewGuid();
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
mockRoleRepository
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
@@ -442,8 +442,8 @@ public class DataSeedServiceTests
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(mockUserRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns((UserEntity?)null);
@@ -472,9 +472,9 @@ public class DataSeedServiceTests
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
IUserRoleRepository mockUserRoleRepository = Substitute.For<IUserRoleRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(mockUserRepository);
_mockUnitOfWork.GetRepository<IUserRoleRepository>().Returns(mockUserRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
_mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository);
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(adminUser);
@@ -498,7 +498,7 @@ public class DataSeedServiceTests
Error expectedError = Error.Failure("Role.NotFound", "Failed to retrieve admin role");
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
mockRoleRepository
.GetByNameAsync("Admin", Arg.Any<CancellationToken>())
@@ -525,8 +525,8 @@ public class DataSeedServiceTests
IRoleRepository mockRoleRepository = Substitute.For<IRoleRepository>();
IUserRepository mockUserRepository = Substitute.For<IUserRepository>();
_mockUnitOfWork.GetRepository<IRoleRepository>().Returns(mockRoleRepository);
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(mockUserRepository);
_mockUnitOfWork.RoleRepository.Returns(mockRoleRepository);
_mockUnitOfWork.UserRepository.Returns(mockUserRepository);
mockRoleRepository.GetByNameAsync("Admin", Arg.Any<CancellationToken>()).Returns(adminRole);
mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>()).Returns(expectedError);
@@ -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()
/// <summary>
/// Provides the repository properties exposed by the unit of work.
/// </summary>
/// <returns>An enumerable of tuples containing the repository property name and its accessor.</returns>
public static IEnumerable<object[]> GetRepositoryProperties()
{
// Arrange
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
// Act
unitOfWork.ResetRepositories();
// Assert
Assert.Equal(0, unitOfWork.Repositories.Count);
yield return new object[] { nameof(IUnitOfWork.PermissionRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.PermissionRepository) };
yield return new object[] { nameof(IUnitOfWork.RolePermissionRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.RolePermissionRepository) };
yield return new object[] { nameof(IUnitOfWork.RoleRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.RoleRepository) };
yield return new object[] { nameof(IUnitOfWork.UserRoleRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.UserRoleRepository) };
yield return new object[] { nameof(IUnitOfWork.BookRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.BookRepository) };
yield return new object[] { nameof(IUnitOfWork.DirectoryScanFingerprintRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.DirectoryScanFingerprintRepository) };
yield return new object[] { nameof(IUnitOfWork.LibraryRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryRepository) };
yield return new object[] { nameof(IUnitOfWork.LibraryScanRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryScanRepository) };
yield return new object[] { nameof(IUnitOfWork.LibraryScanSnapshotRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryScanSnapshotRepository) };
yield return new object[] { nameof(IUnitOfWork.LibraryScanStagingResultsRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryScanStagingResultsRepository) };
yield return new object[] { nameof(IUnitOfWork.LibraryMetadataProviderConfigurationRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.LibraryMetadataProviderConfigurationRepository) };
yield return new object[] { nameof(IUnitOfWork.PluginRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.PluginRepository) };
yield return new object[] { nameof(IUnitOfWork.UserRepository), (Func<UnitOfWork, object>)(unitOfWork => unitOfWork.UserRepository) };
}
[Fact]
public void AddRepositories_WhenCalled_ShouldAddRepositories()
[Theory]
[MemberData(nameof(GetRepositoryProperties))]
public void RepositoryProperty_WhenAccessed_ShouldReturnRepositoryAndCacheInstance(string propertyName, Func<UnitOfWork, object> repositoryAccessor)
{
// Arrange
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
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<IRepositoryFactory>();
LuminaDbContext dbContext = _fixture.Create<LuminaDbContext>();
// 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<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
unitOfWork.ResetRepositories();
// Act
IBookRepository result = unitOfWork.GetRepository<IBookRepository>();
// Assert
Assert.Null(result);
}
[Fact]
public void GetRepository_WhenRepositoriesAdded_ShouldReturnRepositories()
{
// Arrange
ServiceCollection services = new();
DataAccessLayerServices.AddDataAccessLayerServices(services);
services.AddTransient<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
UnitOfWork unitOfWork = (UnitOfWork)serviceProvider.GetRequiredService<IUnitOfWork>();
// Act & Assert
Assert.NotNull(unitOfWork.GetRepository<IBookRepository>());
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<IRepositoryFactory>();
LuminaDbContext dbContext = _fixture.Create<LuminaDbContext>();
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<ICurrentUserService, TestCurrentUserService>();
services.AddTransient<IDateTimeProvider, TestDateTimeProvider>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Act
IUnitOfWork unitOfWork = serviceProvider.GetRequiredService<IUnitOfWork>();
// Assert
Assert.NotNull(unitOfWork.PermissionRepository);
Assert.NotNull(unitOfWork.RoleRepository);
Assert.NotNull(unitOfWork.UserRepository);
}
private UnitOfWork CreateUnitOfWork()
{
return new(_fixture.Create<LuminaDbContext>());
}
}
@@ -41,7 +41,7 @@ public class AuthorizationServiceTests
_mockUserRepository = Substitute.For<IUserRepository>();
_mockAuthorizationPolicyFactory = Substitute.For<IAuthorizationPolicyFactory>();
_mockUnitOfWork.GetRepository<IUserRepository>().Returns(_mockUserRepository);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_sut = new AuthorizationService(_mockUnitOfWork, _mockAuthorizationPolicyFactory);
}