//
// SharedManager.cs
//
// Copyright (c) František Boháček. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NosSmooth.Data.NOSFiles;
using NosSmooth.LocalBinding;
using NosSmooth.PacketSerializer.Packets;
namespace NosSmooth.Extensions.SharedBinding;
///
/// Manager for sharing ,
/// and
/// .
///
public class SharedManager
{
private static SharedManager? _instance;
private NosBindingManager? _bindingManager;
private NostaleDataFilesManager? _filesManager;
private IPacketTypesRepository? _packetRepository;
///
/// A singleton instance.
/// One per process.
///
public static SharedManager Instance
{
get
{
if (_instance is null)
{
_instance = new SharedManager();
}
return _instance;
}
}
///
/// Gets the shared nos binding manager.
///
/// The service provider.
/// The shared manager.
public NosBindingManager GetNosBindingManager(IServiceProvider services)
{
if (_bindingManager is null)
{
_bindingManager = GetFromDescriptor(services, o => o.BindingDescriptor);
}
return _bindingManager;
}
///
/// Gets the shared file manager.
///
/// The service provider.
/// The shared manager.
public NostaleDataFilesManager GetFilesManager(IServiceProvider services)
{
if (_filesManager is null)
{
_filesManager = GetFromDescriptor(services, o => o.FileDescriptor);
}
return _filesManager;
}
///
/// Gets the shared packet type repository.
///
/// The service provider.
/// The shared repository.
public IPacketTypesRepository GetPacketRepository(IServiceProvider services)
{
if (_packetRepository is null)
{
_packetRepository = GetFromDescriptor(services, o => o.PacketRepositoryDescriptor);
}
return _packetRepository;
}
private T GetFromDescriptor(IServiceProvider services, Func getDescriptor)
{
var options = services.GetRequiredService>();
var descriptor = getDescriptor(options.Value);
if (descriptor is null)
{
throw new InvalidOperationException
($"Could not find {typeof(T)} in the service provider when trying to make a shared instance.");
}
if (descriptor.ImplementationInstance is not null)
{
return (T)descriptor.ImplementationInstance;
}
if (descriptor.ImplementationFactory is not null)
{
return (T)descriptor.ImplementationFactory(services);
}
if (descriptor.ImplementationType is not null)
{
return (T)ActivatorUtilities.CreateInstance(services, descriptor.ImplementationType);
}
return ActivatorUtilities.CreateInstance(services);
}
}