Implements Data Access Layer

This commit is contained in:
BinaryAlley committed 2024-08-26 23:32:29 +03:00
1 parent b69e59a3d8
commit 8b729cc16c
24 files changed
+1721 -9

No files matched your search

@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.Models.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Microsoft.EntityFrameworkCore;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Books;
/// <summary>
/// Repository for books.
/// </summary>
internal sealed class BookRepository : IBookRepository
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly LuminaDbContext _luminaDbContext;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="BookRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public BookRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Adds a new book.
/// </summary>
/// <param name="book">The book to add.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{T}"/> representing either a successfull operation, or an error.</returns>
public async Task<ErrorOr<Created>> InsertAsync(BookDto book, CancellationToken cancellationToken)
{
var jobExists = await _luminaDbContext.Books.AnyAsync(_book => _book.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
if (jobExists)
return Errors.WrittenContent.BookAlreadyExists;
_luminaDbContext.Books.Add(book);
return Result.Created;
}
/// <summary>
/// Gets all books.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{T}"/> containing either a collection of <see cref="BookDto"/>, or an error.</returns>
public async Task<ErrorOr<IEnumerable<BookDto>>> GetAllAsync(CancellationToken cancellationToken)
{
return await _luminaDbContext.Books.ToListAsync(cancellationToken).ConfigureAwait(false);
}
#endregion
}
@@ -0,0 +1,16 @@
namespace Lumina.DataAccess.Core.Repositories.Common.Factory;
/// <summary>
/// Repositories abstract factory.
/// </summary>
public interface IRepositoryFactory
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a new repository of type <typeparamref name="TResult"/>.
/// </summary>
/// <typeparam name="TResult">The type of repository to create.</typeparam>
/// <returns>A repository of type <typeparamref name="TResult"/>.</returns>
TResult CreateRepository<TResult>() where TResult : notnull;
#endregion
}
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Common.Factory;
/// <summary>
/// Custom collection for storing repositories.
/// </summary>
public class RepositoryDictionary
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly List<KeyValuePair<Type, object>> _container = [];
#endregion
#region ==================================================================== PROPERTIES =================================================================================
public int Count { get { return _container.Count; } }
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <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;
}
#endregion
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.Extensions.DependencyInjection;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Common.Factory;
/// <summary>
/// Concrete implementation for the repositories abstract factory.
/// </summary>
public class RepositoryFactory : IRepositoryFactory
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IServiceProvider _serviceProvider;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Overload C-tor.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
public RepositoryFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Creates a new repository of type <typeparamref name="TResult"/>.
/// </summary>
/// <typeparam name="TResult">The type of repository to create.</typeparam>
/// <returns>A repository of type <typeparamref name="TResult"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the type of the requested repository has not been registered.</exception>
public TResult CreateRepository<TResult>() where TResult : notnull
{
return _serviceProvider.GetRequiredService<TResult>() ?? throw new ArgumentException();
}
#endregion
}
@@ -0,0 +1,68 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Models.Books;
using Lumina.Application.Common.Models.Common;
using Lumina.Domain.Common.Events;
using Microsoft.EntityFrameworkCore;
#endregion
namespace Lumina.DataAccess.Core.UoW;
/// <summary>
/// DbContext for the Lumina application.
/// </summary>
/// <remarks>To add a new migration: add-migration InitialMigration -p Lumina.DataAccess -s Lumina.Presentation.Api -o Common\Migrations</remarks>
/// <remarks>To update the database: update-database -p Lumina.DataAccess -s Lumina.Presentation.Api</remarks>
public class LuminaDbContext : DbContext
{
#region ==================================================================== PROPERTIES =================================================================================
public DbSet<BookDto> Books { get; set; } = null!;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Overload C-tor.
/// </summary>
/// <param name="options">The options for configuring the database context.</param>
public LuminaDbContext(DbContextOptions<LuminaDbContext> options) : base(options)
{
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Configures the entity mappings for the database context.
/// </summary>
/// <param name="modelBuilder">The model builder used to configure the entity mappings.</param>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// find all the entity configurations in the assembly and apply them
modelBuilder
.Ignore<List<IDomainEvent>>()
.ApplyConfigurationsFromAssembly(typeof(LuminaDbContext).Assembly);
base.OnModelCreating(modelBuilder);
}
/// <summary>
/// Overrides the SaveChanges method of the DbContext class to automatically set the Created and Updated properties of entities that implement the <see cref="IStorageEntity"/>.
/// </summary>
/// <returns>The number of objects written to the underlying database.</returns>
public override int SaveChanges()
{
// get all the entity entries that are either added or modified
var entries = ChangeTracker.Entries()
.Where(e => e.Entity is IStorageEntity &&
(e.State is EntityState.Added or EntityState.Modified));
foreach (var entityEntry in entries)
{
// if the entity is in Added state, set the Created property to the current date and time
if (entityEntry.State == EntityState.Added)
((IStorageEntity)entityEntry.Entity).Created = DateTime.UtcNow;
// otherwise, if the entity is in Modified state, set the Updated property to the current date and time
else if (entityEntry.State == EntityState.Modified)
((IStorageEntity)entityEntry.Entity).Updated = DateTime.UtcNow;
}
return base.SaveChanges();
}
#endregion
}
@@ -0,0 +1,117 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.DataAccess.Core.Repositories.Common.Factory;
using System.Reflection;
#endregion
namespace Lumina.DataAccess.Core.UoW;
/// <summary>
/// Interaction boundary with the Data Access Layer.
/// </summary>
public class UnitOfWork : IUnitOfWork
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly LuminaDbContext _luminaDbContext;
private readonly IRepositoryFactory _repositoryFactory;
#endregion
#region ==================================================================== PROPERTIES =================================================================================
internal RepositoryDictionary Repositories { get; private set; } = new RepositoryDictionary();
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Overload C-tor.
/// </summary>
/// <param name="repositoryFactory">The abstract factory used to generate repositories.</param>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public UnitOfWork(IRepositoryFactory repositoryFactory, LuminaDbContext luminaDbContext)
{
_repositoryFactory = repositoryFactory;
_luminaDbContext = luminaDbContext;
AddRepositories();
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <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 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);
}
}
/// <summary>
/// Exposes a repository of type <typeparamref name="TRepository"/> to the Business Logic Layer.
/// </summary>
/// <typeparam name="TRepository">The type of the exposed repository.</typeparam>
/// <returns>A repository of type <typeparamref name="TRepository"/>.</returns>
public TRepository GetRepository<TRepository>()
{
// 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);
}
/// <summary>
/// Resets the list of repositories.
/// </summary>
internal void ResetRepositories()
{
Repositories.Clear();
}
/// <summary>
/// Saves the changes made to the database.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SaveChangesAsync(CancellationToken cancellationToken)
{
await _luminaDbContext.SaveChangesAsync(cancellationToken);
}
/// <summary>
/// Opens a transaction.
/// </summary>
public void OpenTransaction()
{
throw new NotImplementedException();
}
/// <summary>
/// Commits a transaction.
/// </summary>
public void CommitTransaction()
{
throw new NotImplementedException();
}
#endregion
}