diff --git a/Extensions/XDIKeyedServiceExtensions.cs b/Extensions/XDIKeyedServiceExtensions.cs index aae16cb..7829034 100644 --- a/Extensions/XDIKeyedServiceExtensions.cs +++ b/Extensions/XDIKeyedServiceExtensions.cs @@ -2,10 +2,14 @@ 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 ... /// /// an Internal Class for Registering Keyed Services ... /// @@ -32,13 +36,549 @@ namespace xCommons.Extensions } } + /// + /// Holds the registration metadata for a keyed service. + /// + internal sealed class XKeyedServiceRegistration + where TService : class + { + public string Key { get; private set; } + public bool OwnsInstance { get; private set; } + public ServiceLifetime Lifetime { get; private set; } + public Func Factory { get; private set; } + + public XKeyedServiceRegistration( + string key, + Func factory, + ServiceLifetime lifetime, + bool ownsInstance + ) + { + // + Key = key; + Factory = factory; + Lifetime = lifetime; + OwnsInstance = ownsInstance; + } + } + + /// + /// Reference equality comparer used to avoid disposing the same object twice. + /// Compatible with .NET Standard 2.0. + /// + internal sealed class XReferenceEqualityComparer : IEqualityComparer + { + // + 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); + } + } + + /// + /// Cache used by Singleton and Scoped registrations. + /// It also tracks disposable instances created by Transient registrations. + /// + internal class XKeyedServiceCache : IDisposable + where TService : class + { + // + private bool disposed; + private readonly object sync = new(); + private readonly List disposables = []; + private readonly HashSet trackedInstances = + new(XReferenceEqualityComparer.Instance); + private readonly Dictionary instances = + new(StringComparer.OrdinalIgnoreCase); + + public TService GetOrAdd( + string key, + Func 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).FullName); + } + } + + public void Dispose() + { + // + List 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(); + } + } + } + + /// + /// One cache per DI scope. + /// + internal sealed class XKeyedServiceScopeCache : XKeyedServiceCache + where TService : class + { } + + /// + /// One cache for the root service provider. + /// The provider injected into this Singleton is the root provider. + /// + internal sealed class XKeyedServiceSingletonCache : XKeyedServiceCache + where TService : class + { + // + public IServiceProvider RootProvider { get; private set; } + + public XKeyedServiceSingletonCache(IServiceProvider rootProvider) + { + RootProvider = rootProvider; + } + } + + /// + /// Stores keyed registrations for one service contract. + /// A single registry is shared by all registrations of TService. + /// + internal sealed class XKeyedServiceRegistry + where TService : class + { + // + private readonly object sync = new(); + + private readonly Dictionary> + registrations = + new(StringComparer.OrdinalIgnoreCase); + + public void Add(XKeyedServiceRegistration 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 registration + ) + { + lock (sync) + { + return registrations.TryGetValue(key, out registration); + } + } + } + #endregion + /// /// Keyed Service Extensions Methods ... /// public static class XDIKeyedServiceExtensions { + + // + #region Old ... + // /// + // /// Register Specified Keyed Service ... + // /// + // /// + // /// + // /// + // /// + // /// + // public static void AddXKeyedService( + // this IServiceCollection services, + // string key, + // ServiceLifetime lifetime = ServiceLifetime.Scoped + // ) + // where TService : class + // where TImplementation : TService + // { + // // + // services.AddXKeyedService( + // key: key, + // lifetime: lifetime, + // factory: sp => ActivatorUtilities.CreateInstance(sp) + // ); + // } + + // /// + // /// Register Specified Keyed Service ... + // /// + // /// + // /// + // /// + // /// + // public static void AddXKeyedService( + // this IServiceCollection services, + // string key, + // ServiceLifetime lifetime = ServiceLifetime.Scoped + // ) + // where TService : class + // { + // // + // services.AddXKeyedService( + // key: key, + // lifetime: lifetime, + // factory: sp => ActivatorUtilities.CreateInstance(sp) + // ); + // } + + // /// + // /// Register Specified Keyed Service ... + // /// + // /// + // /// + // /// + // /// + // /// + // public static void AddXKeyedService( + // this IServiceCollection services, + // string key, + // Func 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), + // sp => new XKeyedService(key, factory(sp)), + // lifetime)); + // } + + // /// + // /// Register Specified Keyed Service ... + // /// + // /// + // /// + // /// + // /// + // /// + // public static void AddXKeyedService( + // 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), + // sp => new XKeyedService(key, instance), + // lifetime)); + // } + + // /// + // /// Retrieve Registered XKeyedService ... + // /// + // /// + // /// + // /// + // /// + // public static TService GetXKeyedService( + // this IServiceProvider provider, + // string key + // ) + // where TService : class + // { + // // + // if (provider.IsNull()) + // { + // XException.InvalidArgs.Throw("Invalid Provider ..."); + // } + + // // + // var result = provider + // .GetServices>() + // .LastOrDefault(x => x.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)) + // ?.Instance; + // return result; + // } + + // /// + // /// Retrieve Registered XKeyedService ... + // /// + // /// + // /// + // /// + // /// + // public static TService GetXKeyedService( + // this IServiceCollection provider, + // string key + // ) + // where TService : class + // { + // // + // if (provider.IsNull()) + // { + // XException.InvalidArgs.Throw("Invalid Provider ..."); + // } + + // // + // var result = provider + // .GetRegisteredServices>() + // .LastOrDefault(x => x.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)) + // ?.Instance; + // return result; + // } + + // /// + // /// Retrieve Registered XKeyedService ... + // /// + // /// + // /// + // /// + // /// + // public static TService GetRequiredXKeyedService( + // this IServiceProvider provider, + // string key + // ) + // where TService : class + // { + // // + // var service = provider.GetXKeyedService(key); + // if (service == null) + // { + // // + // XException.InvalidArgs.Throw( + // $"Service '{typeof(TService).FullName}' " + + // $"with key '{key}' is not registered."); + // } + + // // + // return service; + // } + + // /// + // /// Retrieve Registered XKeyedService ... + // /// + // /// + // /// + // /// + // /// + // public static TService GetRequiredXKeyedService( + // this IServiceCollection provider, + // string key + // ) + // where TService : class + // { + // // + // var service = provider.GetXKeyedService(key); + // if (service == null) + // { + // // + // XException.InvalidArgs.Throw( + // $"Service '{typeof(TService).FullName}' " + + // $"with key '{key}' is not registered."); + // } + + // // + // return service; + // } + #endregion + + // + #region Custom ... /// - /// Register Specified Keyed Service ... + /// Registers TImplementation for TService under the specified key ... /// /// /// @@ -51,18 +591,20 @@ namespace xCommons.Extensions ServiceLifetime lifetime = ServiceLifetime.Scoped ) where TService : class - where TImplementation : TService + where TImplementation : class, TService { // - services.AddXKeyedService( + AddXKeyedService( key: key, + services: services, lifetime: lifetime, + ownsInstance: true, factory: sp => ActivatorUtilities.CreateInstance(sp) ); } /// - /// Register Specified Keyed Service ... + /// Registers a concrete TService under the specified key ... /// /// /// @@ -76,151 +618,95 @@ namespace xCommons.Extensions where TService : class { // - services.AddXKeyedService( + AddXKeyedService( key: key, lifetime: lifetime, + services: services, + ownsInstance: true, factory: sp => ActivatorUtilities.CreateInstance(sp) ); } /// - /// Register Specified Keyed Service ... + /// 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 ... /// /// /// /// /// /// + /// public static void AddXKeyedService( this IServiceCollection services, string key, Func factory, - ServiceLifetime lifetime = ServiceLifetime.Scoped + ServiceLifetime lifetime = ServiceLifetime.Scoped, + bool ownsInstance = true ) where TService : class { // - var erorr = new XError(); + ValidateRegistrationArguments( + key: key, + factory: factory, + services: services, + lifetime: lifetime + ); // - var isKeyValid = !key.IsNullOrEmpty(); - var isFactoryValid = !factory.IsNull(); - var isServicesValid = !services.IsNull(); - var isServiceLifetimeValid = Enum.IsDefined(typeof(ServiceLifetime), lifetime); + var registry = GetOrAddRegistry(services); + registry.Add( + new XKeyedServiceRegistration( + key, + factory, + lifetime, + ownsInstance)); - // - 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), - sp => new XKeyedService(key, factory(sp)), - lifetime)); + // The caches are resolved only when a service with the corresponding + // lifetime is requested. + services.TryAddScoped>(); + services.TryAddSingleton>(); } /// - /// Register Specified Keyed Service ... + /// 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 ... /// /// /// /// /// - /// + /// public static void AddXKeyedService( this IServiceCollection services, string key, TService instance, - ServiceLifetime lifetime = ServiceLifetime.Scoped + bool disposeInstance = false ) 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 (instance.IsNull()) { - // - 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(); + ThrowInvalidArgs("Service instance not provided."); } // - services.Add(new ServiceDescriptor( - typeof(XKeyedService), - sp => new XKeyedService(key, instance), - lifetime)); + AddXKeyedService( + key: key, + services: services, + factory: sp => instance, + ownsInstance: disposeInstance, + lifetime: ServiceLifetime.Singleton + ); } /// - /// Retrieve Registered XKeyedService ... + /// Resolves a keyed service. Returns null when the key is not registered ... /// /// /// @@ -235,46 +721,185 @@ namespace xCommons.Extensions // if (provider.IsNull()) { - XException.InvalidArgs.Throw("Invalid Provider ..."); + ThrowInvalidArgs("Invalid service provider ..."); } // - var result = provider - .GetServices>() - .LastOrDefault(x => x.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)) - ?.Instance; - return result; + ValidateKey(key); + + // + var registry = + provider.GetService>(); + if (registry.IsNull()) + { + return null; + } + + // + if (!registry.TryGet(key, out XKeyedServiceRegistration registration)) + { + return null; + } + + // + switch (registration.Lifetime) + { + // + case ServiceLifetime.Singleton: + { + // + var cache = provider + .GetRequiredService>(); + return cache.GetOrAdd( + registration.Key, + () => CreateInstance( + registration, + cache.RootProvider), + registration.OwnsInstance); + } + + // + case ServiceLifetime.Scoped: + { + // + var cache = provider + .GetRequiredService>(); + 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>() + .TrackTransient(instance); + } + + // + return instance; + } + + default: + // + ThrowInvalidArgs( + "Invalid service lifetime for key '" + + registration.Key + "'."); + + // + return null; + } } /// - /// Retrieve Registered XKeyedService ... + /// Resolves a keyed service. Returns null when the key is not registered ... /// /// - /// + /// /// /// public static TService GetXKeyedService( - this IServiceCollection provider, + this IServiceCollection services, string key ) where TService : class { // + var provider = services.BuildServiceProvider(); if (provider.IsNull()) { - XException.InvalidArgs.Throw("Invalid Provider ..."); + ThrowInvalidArgs("Invalid service provider ..."); } // - var result = provider - .GetRegisteredServices>() - .LastOrDefault(x => x.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)) - ?.Instance; - return result; + ValidateKey(key); + + // + var registry = + provider.GetService>(); + if (registry.IsNull()) + { + return null; + } + + // + if (!registry.TryGet(key, out XKeyedServiceRegistration registration)) + { + return null; + } + + // + switch (registration.Lifetime) + { + // + case ServiceLifetime.Singleton: + { + // + var cache = provider + .GetRequiredService>(); + return cache.GetOrAdd( + registration.Key, + () => CreateInstance( + registration, + cache.RootProvider), + registration.OwnsInstance); + } + + // + case ServiceLifetime.Scoped: + { + // + var cache = provider + .GetRequiredService>(); + 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>() + .TrackTransient(instance); + } + + // + return instance; + } + + default: + // + ThrowInvalidArgs( + "Invalid service lifetime for key '" + + registration.Key + "'."); + + // + return null; + } } /// - /// Retrieve Registered XKeyedService ... + /// Resolves a keyed service or throws when the key is not registered ... /// /// /// @@ -288,43 +913,196 @@ namespace xCommons.Extensions { // var service = provider.GetXKeyedService(key); - if (service == null) + if (service.IsNull()) { // - XException.InvalidArgs.Throw( - $"Service '{typeof(TService).FullName}' " + - $"with key '{key}' is not registered."); + ThrowInvalidArgs( + "Service '" + typeof(TService).FullName + + "' with key '" + key + "' is not registered."); } - + // return service; } /// - /// Retrieve Registered XKeyedService ... + /// Resolves a keyed service or throws when the key is not registered ... /// /// - /// + /// /// /// public static TService GetRequiredXKeyedService( - this IServiceCollection provider, + this IServiceCollection services, string key ) where TService : class { // - var service = provider.GetXKeyedService(key); - if (service == null) + var service = services.GetXKeyedService(key); + if (service.IsNull()) { // - XException.InvalidArgs.Throw( - $"Service '{typeof(TService).FullName}' " + - $"with key '{key}' is not registered."); + ThrowInvalidArgs( + "Service '" + typeof(TService).FullName + + "' with key '" + key + "' is not registered."); } - + // return service; } + + /// + /// Checks whether a key is registered in the service collection ... + /// This method does not create or resolve a service instance ... + /// + /// + /// + /// + /// + public static bool IsXKeyedServiceRegistered( + this IServiceCollection services, + string key + ) + where TService : class + { + // + if (services.IsNull()) + { + ThrowInvalidArgs("Invalid service collection."); + } + + // + ValidateKey(key); + + // + var registry = FindRegistry(services); + var result = + !registry.IsNull() && + registry + .TryGet(key, out XKeyedServiceRegistration registration); + + // + return result; + } + #endregion + + // + #region Private ... + private static TService CreateInstance( + XKeyedServiceRegistration 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 GetOrAddRegistry(IServiceCollection services) + where TService : class + { + // + var registry = FindRegistry(services); + if (!registry.IsNull()) + { + return registry; + } + + // + registry = new XKeyedServiceRegistry(); + services.AddSingleton(registry); + + // + return registry; + } + + private static void ValidateRegistrationArguments( + IServiceCollection services, + string key, + Func 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 FindRegistry(IServiceCollection services) + where TService : class + { + // + var descriptor = services.LastOrDefault( + x => x.ServiceType == typeof(XKeyedServiceRegistry)); + if (descriptor.IsNull()) + { + return null; + } + + // + var registry = + descriptor.ImplementationInstance + as XKeyedServiceRegistry; + 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 } } \ No newline at end of file