Files
xCommons/Extensions/XDIKeyedServiceExtensions.cs
T

1108 lines
35 KiB
C#

using System;
using System.Linq;
using xExceptions.Models;
using xExceptions.Constants;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace xCommons.Extensions
{
//
#region Requirements ...
/// <summary>
/// an Internal Class for Registering Keyed Services ...
/// </summary>
/// <typeparam name="TService"></typeparam>
internal sealed class XKeyedService<TService>
where TService : class
{
public string Key { get; }
public TService Instance { get; }
public XKeyedService(
string key,
TService instance
)
{
//
if (key.IsNullOrEmpty() || instance.IsNull())
{
XException.InvalidArgs.Throw();
}
//
Key = key;
Instance = instance;
}
}
/// <summary>
/// Holds the registration metadata for a keyed service.
/// </summary>
internal sealed class XKeyedServiceRegistration<TService>
where TService : class
{
public string Key { get; private set; }
public bool OwnsInstance { get; private set; }
public ServiceLifetime Lifetime { get; private set; }
public Func<IServiceProvider, TService> Factory { get; private set; }
public XKeyedServiceRegistration(
string key,
Func<IServiceProvider, TService> factory,
ServiceLifetime lifetime,
bool ownsInstance
)
{
//
Key = key;
Factory = factory;
Lifetime = lifetime;
OwnsInstance = ownsInstance;
}
}
/// <summary>
/// Reference equality comparer used to avoid disposing the same object twice.
/// Compatible with .NET Standard 2.0.
/// </summary>
internal sealed class XReferenceEqualityComparer : IEqualityComparer<object>
{
//
public static readonly XReferenceEqualityComparer Instance = new();
private XReferenceEqualityComparer()
{ }
public new bool Equals(object x, object y)
{
return ReferenceEquals(x, y);
}
public int GetHashCode(object obj)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}
}
/// <summary>
/// Cache used by Singleton and Scoped registrations.
/// It also tracks disposable instances created by Transient registrations.
/// </summary>
internal class XKeyedServiceCache<TService> : IDisposable
where TService : class
{
//
private bool disposed;
private readonly object sync = new();
private readonly List<IDisposable> disposables = [];
private readonly HashSet<object> trackedInstances =
new(XReferenceEqualityComparer.Instance);
private readonly Dictionary<string, TService> instances =
new(StringComparer.OrdinalIgnoreCase);
public TService GetOrAdd(
string key,
Func<TService> factory,
bool ownsInstance
)
{
//
lock (sync)
{
//
ThrowIfDisposed();
if (instances.TryGetValue(key, out TService instance))
{
return instance;
}
//
instance = factory();
if (instance == null)
{
//
XDIKeyedServiceExtensions.ThrowInvalidArgs(
"The factory for keyed service '" + key +
"' returned null.");
}
//
instances.Add(key, instance);
if (ownsInstance)
{
TrackDisposable(instance);
}
//
return instance;
}
}
public void TrackTransient(TService instance)
{
//
if (instance == null)
{
//
XDIKeyedServiceExtensions.ThrowInvalidArgs(
"A transient keyed service instance cannot be null.");
}
//
lock (sync)
{
//
ThrowIfDisposed();
TrackDisposable(instance);
}
}
private void TrackDisposable(object instance)
{
//
if (instance is IDisposable disposable && trackedInstances.Add(instance))
{
disposables.Add(disposable);
}
}
private void ThrowIfDisposed()
{
//
if (disposed)
{
throw new ObjectDisposedException(
typeof(XKeyedServiceCache<TService>).FullName);
}
}
public void Dispose()
{
//
List<IDisposable> disposables;
lock (sync)
{
//
if (disposed)
{
return;
}
//
disposed = true;
disposables = [.. this.disposables];
this.disposables.Clear();
instances.Clear();
trackedInstances.Clear();
}
//
// Dispose in reverse creation order.
for (var i = disposables.Count - 1; i >= 0; i--)
{
disposables[i].Dispose();
}
}
}
/// <summary>
/// One cache per DI scope.
/// </summary>
internal sealed class XKeyedServiceScopeCache<TService> : XKeyedServiceCache<TService>
where TService : class
{ }
/// <summary>
/// One cache for the root service provider.
/// The provider injected into this Singleton is the root provider.
/// </summary>
internal sealed class XKeyedServiceSingletonCache<TService> : XKeyedServiceCache<TService>
where TService : class
{
//
public IServiceProvider RootProvider { get; private set; }
public XKeyedServiceSingletonCache(IServiceProvider rootProvider)
{
RootProvider = rootProvider;
}
}
/// <summary>
/// Stores keyed registrations for one service contract.
/// A single registry is shared by all registrations of TService.
/// </summary>
internal sealed class XKeyedServiceRegistry<TService>
where TService : class
{
//
private readonly object sync = new();
private readonly Dictionary<string, XKeyedServiceRegistration<TService>>
registrations =
new(StringComparer.OrdinalIgnoreCase);
public void Add(XKeyedServiceRegistration<TService> registration)
{
//
lock (sync)
{
//
if (registrations.ContainsKey(registration.Key))
{
//
XDIKeyedServiceExtensions.ThrowInvalidArgs(
"A keyed service with key '" + registration.Key +
"' is already registered for '" +
typeof(TService).FullName + "'.");
}
//
registrations.Add(registration.Key, registration);
}
}
public bool TryGet(
string key,
out XKeyedServiceRegistration<TService> registration
)
{
lock (sync)
{
return registrations.TryGetValue(key, out registration);
}
}
}
#endregion
/// <summary>
/// Keyed Service Extensions Methods ...
/// </summary>
public static class XDIKeyedServiceExtensions
{
//
#region Old ...
// /// <summary>
// /// Register Specified Keyed Service ...
// /// </summary>
// /// <typeparam name="TService"></typeparam>
// /// <typeparam name="TImplementation"></typeparam>
// /// <param name="services"></param>
// /// <param name="key"></param>
// /// <param name="lifetime"></param>
// public static void AddXKeyedService<TService, TImplementation>(
// this IServiceCollection services,
// string key,
// ServiceLifetime lifetime = ServiceLifetime.Scoped
// )
// where TService : class
// where TImplementation : TService
// {
// //
// services.AddXKeyedService<TService>(
// key: key,
// lifetime: lifetime,
// factory: sp => ActivatorUtilities.CreateInstance<TImplementation>(sp)
// );
// }
// /// <summary>
// /// Register Specified Keyed Service ...
// /// </summary>
// /// <typeparam name="TService"></typeparam>
// /// <param name="services"></param>
// /// <param name="key"></param>
// /// <param name="lifetime"></param>
// public static void AddXKeyedService<TService>(
// this IServiceCollection services,
// string key,
// ServiceLifetime lifetime = ServiceLifetime.Scoped
// )
// where TService : class
// {
// //
// services.AddXKeyedService<TService>(
// key: key,
// lifetime: lifetime,
// factory: sp => ActivatorUtilities.CreateInstance<TService>(sp)
// );
// }
// /// <summary>
// /// Register Specified Keyed Service ...
// /// </summary>
// /// <typeparam name="TService"></typeparam>
// /// <param name="services"></param>
// /// <param name="key"></param>
// /// <param name="factory"></param>
// /// <param name="lifetime"></param>
// public static void AddXKeyedService<TService>(
// this IServiceCollection services,
// string key,
// Func<IServiceProvider, TService> factory,
// ServiceLifetime lifetime = ServiceLifetime.Scoped
// )
// where TService : class
// {
// //
// var erorr = new XError();
// //
// var isKeyValid = !key.IsNullOrEmpty();
// var isFactoryValid = !factory.IsNull();
// var isServicesValid = !services.IsNull();
// var isServiceLifetimeValid = Enum.IsDefined(typeof(ServiceLifetime), lifetime);
// //
// if (!isKeyValid ||
// !isFactoryValid ||
// !isServicesValid ||
// !isServiceLifetimeValid
// )
// {
// //
// if (!isKeyValid)
// {
// erorr.Message = $"Key not Provided ...";
// }
// //
// if (!isFactoryValid)
// {
// erorr.Message = $"Service Factory not Provided ...";
// }
// //
// if (!isServicesValid)
// {
// erorr.Message = $"Services not Provided ...";
// }
// //
// if (!isServiceLifetimeValid)
// {
// erorr.Message = $"invalid Service Lifetime ...";
// }
// //
// erorr.Id = (int)XException.InvalidArgs;
// throw erorr.ToException();
// }
// //
// services.Add(new ServiceDescriptor(
// typeof(XKeyedService<TService>),
// sp => new XKeyedService<TService>(key, factory(sp)),
// lifetime));
// }
// /// <summary>
// /// Register Specified Keyed Service ...
// /// </summary>
// /// <typeparam name="TService"></typeparam>
// /// <param name="services"></param>
// /// <param name="key"></param>
// /// <param name="instance"></param>
// /// <param name="lifetime"></param>
// public static void AddXKeyedService<TService>(
// this IServiceCollection services,
// string key,
// TService instance,
// ServiceLifetime lifetime = ServiceLifetime.Scoped
// )
// where TService : class
// {
// //
// var erorr = new XError();
// //
// var isKeyValid = !key.IsNullOrEmpty();
// var isInstanceValid = !instance.IsNull();
// var isServicesValid = !services.IsNull();
// var isServiceLifetimeValid = Enum.IsDefined(typeof(ServiceLifetime), lifetime);
// //
// if (!isKeyValid ||
// !isInstanceValid ||
// !isServicesValid ||
// !isServiceLifetimeValid
// )
// {
// //
// if (!isKeyValid)
// {
// erorr.Message = $"Key not Provided ...";
// }
// //
// if (!isInstanceValid)
// {
// erorr.Message = $"Instance not Provided ...";
// }
// //
// if (!isServicesValid)
// {
// erorr.Message = $"Services not Provided ...";
// }
// //
// if (!isServiceLifetimeValid)
// {
// erorr.Message = $"invalid Service Lifetime ...";
// }
// //
// erorr.Id = (int)XException.InvalidArgs;
// throw erorr.ToException();
// }
// //
// services.Add(new ServiceDescriptor(
// typeof(XKeyedService<TService>),
// sp => new XKeyedService<TService>(key, instance),
// lifetime));
// }
// /// <summary>
// /// Retrieve Registered XKeyedService ...
// /// </summary>
// /// <typeparam name="TService"></typeparam>
// /// <param name="provider"></param>
// /// <param name="key"></param>
// /// <returns></returns>
// public static TService GetXKeyedService<TService>(
// this IServiceProvider provider,
// string key
// )
// where TService : class
// {
// //
// if (provider.IsNull())
// {
// XException.InvalidArgs.Throw("Invalid Provider ...");
// }
// //
// var result = provider
// .GetServices<XKeyedService<TService>>()
// .LastOrDefault(x => x.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase))
// ?.Instance;
// return result;
// }
// /// <summary>
// /// Retrieve Registered XKeyedService ...
// /// </summary>
// /// <typeparam name="TService"></typeparam>
// /// <param name="provider"></param>
// /// <param name="key"></param>
// /// <returns></returns>
// public static TService GetXKeyedService<TService>(
// this IServiceCollection provider,
// string key
// )
// where TService : class
// {
// //
// if (provider.IsNull())
// {
// XException.InvalidArgs.Throw("Invalid Provider ...");
// }
// //
// var result = provider
// .GetRegisteredServices<XKeyedService<TService>>()
// .LastOrDefault(x => x.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase))
// ?.Instance;
// return result;
// }
// /// <summary>
// /// Retrieve Registered XKeyedService ...
// /// </summary>
// /// <typeparam name="TService"></typeparam>
// /// <param name="provider"></param>
// /// <param name="key"></param>
// /// <returns></returns>
// public static TService GetRequiredXKeyedService<TService>(
// this IServiceProvider provider,
// string key
// )
// where TService : class
// {
// //
// var service = provider.GetXKeyedService<TService>(key);
// if (service == null)
// {
// //
// XException.InvalidArgs.Throw(
// $"Service '{typeof(TService).FullName}' " +
// $"with key '{key}' is not registered.");
// }
// //
// return service;
// }
// /// <summary>
// /// Retrieve Registered XKeyedService ...
// /// </summary>
// /// <typeparam name="TService"></typeparam>
// /// <param name="provider"></param>
// /// <param name="key"></param>
// /// <returns></returns>
// public static TService GetRequiredXKeyedService<TService>(
// this IServiceCollection provider,
// string key
// )
// where TService : class
// {
// //
// var service = provider.GetXKeyedService<TService>(key);
// if (service == null)
// {
// //
// XException.InvalidArgs.Throw(
// $"Service '{typeof(TService).FullName}' " +
// $"with key '{key}' is not registered.");
// }
// //
// return service;
// }
#endregion
//
#region Custom ...
/// <summary>
/// Registers TImplementation for TService under the specified key ...
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <typeparam name="TImplementation"></typeparam>
/// <param name="services"></param>
/// <param name="key"></param>
/// <param name="lifetime"></param>
public static void AddXKeyedService<TService, TImplementation>(
this IServiceCollection services,
string key,
ServiceLifetime lifetime = ServiceLifetime.Scoped
)
where TService : class
where TImplementation : class, TService
{
//
AddXKeyedService<TService>(
key: key,
services: services,
lifetime: lifetime,
ownsInstance: true,
factory: sp => ActivatorUtilities.CreateInstance<TImplementation>(sp)
);
}
/// <summary>
/// Registers a concrete TService under the specified key ...
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <param name="services"></param>
/// <param name="key"></param>
/// <param name="lifetime"></param>
public static void AddXKeyedService<TService>(
this IServiceCollection services,
string key,
ServiceLifetime lifetime = ServiceLifetime.Scoped
)
where TService : class
{
//
AddXKeyedService(
key: key,
lifetime: lifetime,
services: services,
ownsInstance: true,
factory: sp => ActivatorUtilities.CreateInstance<TService>(sp)
);
}
/// <summary>
/// Registers a keyed service using a factory.
/// The factory-created instance is owned and disposed by this keyed-service
/// mechanism by default. Set ownsInstance to false when the factory returns
/// an instance already owned by another DI registration or external owner ...
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <param name="services"></param>
/// <param name="key"></param>
/// <param name="factory"></param>
/// <param name="lifetime"></param>
/// <param name="ownsInstance"></param>
public static void AddXKeyedService<TService>(
this IServiceCollection services,
string key,
Func<IServiceProvider, TService> factory,
ServiceLifetime lifetime = ServiceLifetime.Scoped,
bool ownsInstance = true
)
where TService : class
{
//
ValidateRegistrationArguments(
key: key,
factory: factory,
services: services,
lifetime: lifetime
);
//
var registry = GetOrAddRegistry<TService>(services);
registry.Add(
new XKeyedServiceRegistration<TService>(
key,
factory,
lifetime,
ownsInstance));
// The caches are resolved only when a service with the corresponding
// lifetime is requested.
services.TryAddScoped<XKeyedServiceScopeCache<TService>>();
services.TryAddSingleton<XKeyedServiceSingletonCache<TService>>();
}
/// <summary>
/// Registers an existing instance. The instance is treated as Singleton.
/// The caller retains ownership by default; set disposeInstance to true
/// if this registration should dispose it with the root provider ...
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <param name="services"></param>
/// <param name="key"></param>
/// <param name="instance"></param>
/// <param name="disposeInstance"></param>
public static void AddXKeyedService<TService>(
this IServiceCollection services,
string key,
TService instance,
bool disposeInstance = false
)
where TService : class
{
//
if (instance.IsNull())
{
ThrowInvalidArgs("Service instance not provided.");
}
//
AddXKeyedService(
key: key,
services: services,
factory: sp => instance,
ownsInstance: disposeInstance,
lifetime: ServiceLifetime.Singleton
);
}
/// <summary>
/// Resolves a keyed service. Returns null when the key is not registered ...
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <param name="provider"></param>
/// <param name="key"></param>
/// <returns></returns>
public static TService GetXKeyedService<TService>(
this IServiceProvider provider,
string key
)
where TService : class
{
//
if (provider.IsNull())
{
ThrowInvalidArgs("Invalid service provider ...");
}
//
ValidateKey(key);
//
var registry =
provider.GetService<XKeyedServiceRegistry<TService>>();
if (registry.IsNull())
{
return null;
}
//
if (!registry.TryGet(key, out XKeyedServiceRegistration<TService> registration))
{
return null;
}
//
switch (registration.Lifetime)
{
//
case ServiceLifetime.Singleton:
{
//
var cache = provider
.GetRequiredService<XKeyedServiceSingletonCache<TService>>();
return cache.GetOrAdd(
registration.Key,
() => CreateInstance(
registration,
cache.RootProvider),
registration.OwnsInstance);
}
//
case ServiceLifetime.Scoped:
{
//
var cache = provider
.GetRequiredService<XKeyedServiceScopeCache<TService>>();
return cache.GetOrAdd(
registration.Key,
() => CreateInstance(registration, provider),
registration.OwnsInstance);
}
case ServiceLifetime.Transient:
{
//
var instance = CreateInstance(registration, provider);
//
// The scope cache tracks disposable transient instances,
// but does not cache the instances themselves.
if (registration.OwnsInstance)
{
//
provider
.GetRequiredService<XKeyedServiceScopeCache<TService>>()
.TrackTransient(instance);
}
//
return instance;
}
default:
//
ThrowInvalidArgs(
"Invalid service lifetime for key '" +
registration.Key + "'.");
//
return null;
}
}
/// <summary>
/// Resolves a keyed service. Returns null when the key is not registered ...
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <param name="services"></param>
/// <param name="key"></param>
/// <returns></returns>
public static TService GetXKeyedService<TService>(
this IServiceCollection services,
string key
)
where TService : class
{
//
var provider = services.BuildServiceProvider();
if (provider.IsNull())
{
ThrowInvalidArgs("Invalid service provider ...");
}
//
ValidateKey(key);
//
var registry =
provider.GetService<XKeyedServiceRegistry<TService>>();
if (registry.IsNull())
{
return null;
}
//
if (!registry.TryGet(key, out XKeyedServiceRegistration<TService> registration))
{
return null;
}
//
switch (registration.Lifetime)
{
//
case ServiceLifetime.Singleton:
{
//
var cache = provider
.GetRequiredService<XKeyedServiceSingletonCache<TService>>();
return cache.GetOrAdd(
registration.Key,
() => CreateInstance(
registration,
cache.RootProvider),
registration.OwnsInstance);
}
//
case ServiceLifetime.Scoped:
{
//
var cache = provider
.GetRequiredService<XKeyedServiceScopeCache<TService>>();
return cache.GetOrAdd(
registration.Key,
() => CreateInstance(registration, provider),
registration.OwnsInstance);
}
case ServiceLifetime.Transient:
{
//
var instance = CreateInstance(registration, provider);
//
// The scope cache tracks disposable transient instances,
// but does not cache the instances themselves.
if (registration.OwnsInstance)
{
//
provider
.GetRequiredService<XKeyedServiceScopeCache<TService>>()
.TrackTransient(instance);
}
//
return instance;
}
default:
//
ThrowInvalidArgs(
"Invalid service lifetime for key '" +
registration.Key + "'.");
//
return null;
}
}
/// <summary>
/// Resolves a keyed service or throws when the key is not registered ...
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <param name="provider"></param>
/// <param name="key"></param>
/// <returns></returns>
public static TService GetRequiredXKeyedService<TService>(
this IServiceProvider provider,
string key
)
where TService : class
{
//
var service = provider.GetXKeyedService<TService>(key);
if (service.IsNull())
{
//
ThrowInvalidArgs(
"Service '" + typeof(TService).FullName +
"' with key '" + key + "' is not registered.");
}
//
return service;
}
/// <summary>
/// Resolves a keyed service or throws when the key is not registered ...
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <param name="services"></param>
/// <param name="key"></param>
/// <returns></returns>
public static TService GetRequiredXKeyedService<TService>(
this IServiceCollection services,
string key
)
where TService : class
{
//
var service = services.GetXKeyedService<TService>(key);
if (service.IsNull())
{
//
ThrowInvalidArgs(
"Service '" + typeof(TService).FullName +
"' with key '" + key + "' is not registered.");
}
//
return service;
}
/// <summary>
/// Checks whether a key is registered in the service collection ...
/// This method does not create or resolve a service instance ...
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <param name="services"></param>
/// <param name="key"></param>
/// <returns></returns>
public static bool IsXKeyedServiceRegistered<TService>(
this IServiceCollection services,
string key
)
where TService : class
{
//
if (services.IsNull())
{
ThrowInvalidArgs("Invalid service collection.");
}
//
ValidateKey(key);
//
var registry = FindRegistry<TService>(services);
var result =
!registry.IsNull() &&
registry
.TryGet(key, out XKeyedServiceRegistration<TService> registration);
//
return result;
}
#endregion
//
#region Private ...
private static TService CreateInstance<TService>(
XKeyedServiceRegistration<TService> registration,
IServiceProvider provider
)
where TService : class
{
//
var instance = registration.Factory(provider);
if (instance.IsNull())
{
//
ThrowInvalidArgs(
"The factory for keyed service '" +
registration.Key + "' returned null.");
}
//
return instance;
}
private static XKeyedServiceRegistry<TService> GetOrAddRegistry<TService>(IServiceCollection services)
where TService : class
{
//
var registry = FindRegistry<TService>(services);
if (!registry.IsNull())
{
return registry;
}
//
registry = new XKeyedServiceRegistry<TService>();
services.AddSingleton(registry);
//
return registry;
}
private static void ValidateRegistrationArguments<TService>(
IServiceCollection services,
string key,
Func<IServiceProvider, TService> factory,
ServiceLifetime lifetime
)
where TService : class
{
if (services.IsNull())
{
ThrowInvalidArgs("Service collection not provided.");
}
//
ValidateKey(key);
//
if (factory.IsNull())
{
ThrowInvalidArgs("Service factory not provided.");
}
//
if (!Enum.IsDefined(typeof(ServiceLifetime), lifetime))
{
ThrowInvalidArgs("Invalid service lifetime.");
}
}
private static XKeyedServiceRegistry<TService> FindRegistry<TService>(IServiceCollection services)
where TService : class
{
//
var descriptor = services.LastOrDefault(
x => x.ServiceType == typeof(XKeyedServiceRegistry<TService>));
if (descriptor.IsNull())
{
return null;
}
//
var registry =
descriptor.ImplementationInstance
as XKeyedServiceRegistry<TService>;
if (registry.IsNull())
{
//
ThrowInvalidArgs(
"The keyed-service registry for '" +
typeof(TService).FullName +
"' has an unsupported registration.");
}
//
return registry;
}
private static void ValidateKey(string key)
{
//
if (key.IsNullOrEmpty())
{
ThrowInvalidArgs("Key not provided.");
}
}
internal static void ThrowInvalidArgs(string message)
{
var error = new XError
{
Id = (int)XException.InvalidArgs,
Message = message
};
throw error.ToException();
}
#endregion
}
}