//
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace MUnique.OpenMU.Persistence.EntityFramework;
using System.Threading;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MUnique.OpenMU.Persistence.EntityFramework.Json;
using MUnique.OpenMU.Persistence.EntityFramework.Model;
///
/// The game configuration repository, which loads the configuration by using the
/// , to speed up loading the whole object graph.
///
internal class GameConfigurationRepository : GenericRepository
{
private readonly JsonObjectLoader _objectLoader;
///
/// Initializes a new instance of the class.
///
/// The repository provider.
/// The logger factory.
/// The change publisher.
public GameConfigurationRepository(IContextAwareRepositoryProvider repositoryProvider, ILoggerFactory loggerFactory, IConfigurationChangeListener? changeListener)
: base(repositoryProvider, loggerFactory, changeListener)
{
this._objectLoader = new GameConfigurationJsonObjectLoader();
}
///
public override async ValueTask GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
{
var currentContext = this.RepositoryProvider.ContextStack.GetCurrentContext() as EntityFrameworkContextBase;
if (currentContext is null)
{
throw new InvalidOperationException("There is no current context set.");
}
var database = currentContext.Context.Database;
await database.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
try
{
if (await this._objectLoader.LoadObjectAsync(id, currentContext.Context, cancellationToken).ConfigureAwait(false) is { } config)
{
currentContext.Context.Attach(config);
return config;
}
return null;
}
finally
{
await database.CloseConnectionAsync().ConfigureAwait(false);
}
}
///
public override async ValueTask> GetAllAsync(CancellationToken cancellationToken = default)
{
var currentContext = this.RepositoryProvider.ContextStack.GetCurrentContext() as EntityFrameworkContextBase;
if (currentContext is null)
{
throw new InvalidOperationException("There is no current context set.");
}
var database = currentContext.Context.Database;
await database.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
try
{
var configs = (await this._objectLoader.LoadAllObjectsAsync(currentContext.Context, cancellationToken).ConfigureAwait(false)).ToList();
configs.ForEach(c => currentContext.Context.Attach(c));
return configs;
}
finally
{
await database.CloseConnectionAsync().ConfigureAwait(false);
}
}
}