//
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace MUnique.OpenMU.Persistence;
///
/// The base repository provider.
///
public class BaseRepositoryProvider : IRepositoryProvider
{
private bool _isInitialized;
///
/// Gets the repositories for each entity type.
///
protected IDictionary Repositories { get; } = new Dictionary();
///
/// Gets the repository of the specified generic type.
///
/// The generic type.
/// The repository of the specified generic type.
public virtual IRepository? GetRepository()
where T : class
{
var repository = this.GetRepository(typeof(T));
if (repository is null)
{
return null;
}
// TODO: Not always an adapter is required. Also, the adapter could be cached.
return new RepositoryAdapter(repository);
}
///
/// Gets the repository of the specified generic type.
///
/// The generic type.
/// The type of the repository.
///
/// The repository of the specified generic type.
///
public TRepository? GetRepository()
where T : class
where TRepository : IRepository
{
return (TRepository?)this.GetRepository(typeof(T));
}
///
/// Gets the repository of the specified type.
///
/// Type of the object.
/// The repository of the specified type.
public virtual IRepository? GetRepository(Type objectType)
{
var repository = this.InternalGetRepository(objectType);
return repository;
}
///
/// Initializes this instance.
///
protected virtual void Initialize()
{
}
///
/// Gets the repository of the specified type.
///
/// Type of the object.
/// The repository of the specified type.
protected IRepository? InternalGetRepository(Type objectType)
{
this.EnsureInitialized();
Type? currentSearchType = objectType;
do
{
if (currentSearchType is null)
{
break;
}
if (this.Repositories.TryGetValue(currentSearchType, out var repository))
{
return repository as IRepository;
}
if (currentSearchType.Name != currentSearchType.BaseType?.Name)
{
break;
}
currentSearchType = currentSearchType.BaseType;
}
while (currentSearchType != typeof(object));
return null;
}
///
/// Registers the repository.
///
/// The generic type which the repository handles.
/// The repository.
protected void RegisterRepository(IRepository repository)
where T : class
{
this.RegisterRepository(typeof(T), repository);
}
///
/// Registers the repository.
///
/// The generic type which the repository handles.
/// The repository.
protected virtual void RegisterRepository(Type type, IRepository repository)
{
this.Repositories.Add(type, repository);
}
private void EnsureInitialized()
{
if (!this._isInitialized)
{
this.Initialize();
this._isInitialized = true;
}
}
}