| | | 1 | | using System.Diagnostics.CodeAnalysis; |
| | | 2 | | |
| | | 3 | | using Microsoft.Extensions.DependencyInjection; |
| | | 4 | | |
| | | 5 | | namespace NexusLabs.Needlr; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Extension methods for <see cref="IServiceCollection"/> that add decorator wiring, service inspection, |
| | | 9 | | /// and registration-check utilities to the standard Microsoft DI container. |
| | | 10 | | /// </summary> |
| | | 11 | | /// <remarks> |
| | | 12 | | /// <para> |
| | | 13 | | /// The primary extension in this class is <c>AddDecorator</c>, which wraps an already-registered |
| | | 14 | | /// service with a decorator while preserving the original service's lifetime. This complements |
| | | 15 | | /// the attribute-based <see cref="DecoratorForAttribute{TService}"/> used with Needlr's |
| | | 16 | | /// source generation and reflection scanning. |
| | | 17 | | /// </para> |
| | | 18 | | /// </remarks> |
| | | 19 | | public static class ServiceCollectionExtensions |
| | | 20 | | { |
| | | 21 | | /// <summary> |
| | | 22 | | /// Decorates an existing service registration with a decorator type, preserving the original service's lifetime. |
| | | 23 | | /// The decorator must implement the service interface and take the service interface as a constructor parameter. |
| | | 24 | | /// Works with both interfaces and class types. |
| | | 25 | | /// </summary> |
| | | 26 | | /// <typeparam name="TService">The service type (interface or class) to decorate.</typeparam> |
| | | 27 | | /// <typeparam name="TDecorator">The decorator type that implements TService.</typeparam> |
| | | 28 | | /// <param name="services">The service collection to modify.</param> |
| | | 29 | | /// <returns>The service collection for method chaining.</returns> |
| | | 30 | | /// <exception cref="ArgumentNullException">Thrown when services is null.</exception> |
| | | 31 | | /// <exception cref="InvalidOperationException">Thrown when no service registration is found for TService.</exceptio |
| | | 32 | | /// <example> |
| | | 33 | | /// <code> |
| | | 34 | | /// // Register the original service |
| | | 35 | | /// services.AddScoped<IMyService, MyService>(); |
| | | 36 | | /// |
| | | 37 | | /// // Decorate it while preserving the scoped lifetime |
| | | 38 | | /// services.AddDecorator<IMyService, MyServiceDecorator>(); |
| | | 39 | | /// </code> |
| | | 40 | | /// </example> |
| | | 41 | | public static IServiceCollection AddDecorator<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.P |
| | | 42 | | where TDecorator : class, TService |
| | | 43 | | { |
| | 2443 | 44 | | ArgumentNullException.ThrowIfNull(services); |
| | | 45 | | |
| | | 46 | | // Find ALL existing service registrations for this type |
| | 2442 | 47 | | var existingDescriptors = services |
| | 580101 | 48 | | .Where(d => d.ServiceType == typeof(TService)) |
| | 2442 | 49 | | .ToList(); |
| | | 50 | | |
| | 2442 | 51 | | if (existingDescriptors.Count == 0) |
| | | 52 | | { |
| | 1 | 53 | | throw new InvalidOperationException( |
| | 1 | 54 | | $"No service registration found for type {typeof(TService).Name}. " + |
| | 1 | 55 | | $"Please register the service before decorating it."); |
| | | 56 | | } |
| | | 57 | | |
| | | 58 | | // Remove all existing registrations |
| | 11248 | 59 | | foreach (var descriptor in existingDescriptors) |
| | | 60 | | { |
| | 3183 | 61 | | services.Remove(descriptor); |
| | | 62 | | } |
| | | 63 | | |
| | | 64 | | // Create decorated registrations for each, preserving order and lifetime |
| | 11248 | 65 | | foreach (var existingDescriptor in existingDescriptors) |
| | | 66 | | { |
| | 3183 | 67 | | var decoratedDescriptor = CreateDecoratedDescriptor<TService, TDecorator>(existingDescriptor); |
| | 3183 | 68 | | services.Add(decoratedDescriptor); |
| | | 69 | | } |
| | | 70 | | |
| | 2441 | 71 | | return services; |
| | | 72 | | } |
| | | 73 | | |
| | | 74 | | private static ServiceDescriptor CreateDecoratedDescriptor<TService, [DynamicallyAccessedMembers(DynamicallyAccessed |
| | | 75 | | ServiceDescriptor existingDescriptor) |
| | | 76 | | where TDecorator : class, TService |
| | | 77 | | { |
| | 3183 | 78 | | return existingDescriptor.Lifetime switch |
| | 3183 | 79 | | { |
| | 3173 | 80 | | ServiceLifetime.Singleton => new ServiceDescriptor(typeof(TService), provider => |
| | 3173 | 81 | | { |
| | 138 | 82 | | var originalService = CreateOriginalService<TService>(provider, existingDescriptor); |
| | 138 | 83 | | return ActivatorUtilities.CreateInstance<TDecorator>(provider, originalService!); |
| | 3173 | 84 | | }, ServiceLifetime.Singleton), |
| | 7 | 85 | | ServiceLifetime.Scoped => new ServiceDescriptor(typeof(TService), provider => |
| | 7 | 86 | | { |
| | 13 | 87 | | var originalService = CreateOriginalService<TService>(provider, existingDescriptor); |
| | 13 | 88 | | return ActivatorUtilities.CreateInstance<TDecorator>(provider, originalService!); |
| | 7 | 89 | | }, ServiceLifetime.Scoped), |
| | 3 | 90 | | ServiceLifetime.Transient => new ServiceDescriptor(typeof(TService), provider => |
| | 3 | 91 | | { |
| | 5 | 92 | | var originalService = CreateOriginalService<TService>(provider, existingDescriptor); |
| | 5 | 93 | | return ActivatorUtilities.CreateInstance<TDecorator>(provider, originalService!); |
| | 3 | 94 | | }, ServiceLifetime.Transient), |
| | 0 | 95 | | _ => throw new InvalidOperationException( |
| | 0 | 96 | | $"Unsupported service lifetime '{existingDescriptor.Lifetime}' " + |
| | 0 | 97 | | $"for '{typeof(TService)}'.") |
| | 3183 | 98 | | }; |
| | | 99 | | } |
| | | 100 | | |
| | | 101 | | /// <summary> |
| | | 102 | | /// Decorates an existing service registration with a decorator type, preserving the original service's lifetime. |
| | | 103 | | /// The decorator must implement the service interface and take the service interface as a constructor parameter. |
| | | 104 | | /// Works with both interfaces and class types. |
| | | 105 | | /// </summary> |
| | | 106 | | /// <param name="services">The service collection to modify.</param> |
| | | 107 | | /// <param name="serviceType">The service type (interface or class) to decorate.</param> |
| | | 108 | | /// <param name="decoratorType">The decorator type that implements the service type.</param> |
| | | 109 | | /// <returns>The service collection for method chaining.</returns> |
| | | 110 | | /// <exception cref="ArgumentNullException">Thrown when services, serviceType, or decoratorType is null.</exception> |
| | | 111 | | /// <exception cref="InvalidOperationException">Thrown when no service registration is found for the service type.</ |
| | | 112 | | /// <example> |
| | | 113 | | /// <code> |
| | | 114 | | /// // Register the original service |
| | | 115 | | /// services.AddScoped<IMyService, MyService>(); |
| | | 116 | | /// |
| | | 117 | | /// // Decorate it while preserving the scoped lifetime |
| | | 118 | | /// services.AddDecorator(typeof(IMyService), typeof(MyServiceDecorator)); |
| | | 119 | | /// </code> |
| | | 120 | | /// </example> |
| | | 121 | | public static IServiceCollection AddDecorator( |
| | | 122 | | this IServiceCollection services, |
| | | 123 | | Type serviceType, |
| | | 124 | | [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type decoratorType) |
| | | 125 | | { |
| | 1230 | 126 | | ArgumentNullException.ThrowIfNull(services); |
| | 1230 | 127 | | ArgumentNullException.ThrowIfNull(serviceType); |
| | 1230 | 128 | | ArgumentNullException.ThrowIfNull(decoratorType); |
| | | 129 | | |
| | | 130 | | // Find ALL existing service registrations for this type |
| | 1230 | 131 | | var existingDescriptors = services |
| | 327744 | 132 | | .Where(d => d.ServiceType == serviceType) |
| | 1230 | 133 | | .ToList(); |
| | | 134 | | |
| | 1230 | 135 | | if (existingDescriptors.Count == 0) |
| | | 136 | | { |
| | 0 | 137 | | throw new InvalidOperationException( |
| | 0 | 138 | | $"No service registration found for type {serviceType.Name}. " + |
| | 0 | 139 | | $"Please register the service before decorating it."); |
| | | 140 | | } |
| | | 141 | | |
| | | 142 | | // Remove all existing registrations |
| | 6150 | 143 | | foreach (var descriptor in existingDescriptors) |
| | | 144 | | { |
| | 1845 | 145 | | services.Remove(descriptor); |
| | | 146 | | } |
| | | 147 | | |
| | | 148 | | // Create decorated registrations for each, preserving order and lifetime |
| | 6150 | 149 | | foreach (var existingDescriptor in existingDescriptors) |
| | | 150 | | { |
| | 1845 | 151 | | var decoratedDescriptor = new ServiceDescriptor( |
| | 1845 | 152 | | serviceType, |
| | 1845 | 153 | | provider => |
| | 1845 | 154 | | { |
| | 81 | 155 | | var originalService = CreateOriginalService(provider, existingDescriptor, serviceType); |
| | 81 | 156 | | return ActivatorUtilities.CreateInstance(provider, decoratorType, originalService!); |
| | 1845 | 157 | | }, |
| | 1845 | 158 | | existingDescriptor.Lifetime); |
| | 1845 | 159 | | services.Add(decoratedDescriptor); |
| | | 160 | | } |
| | | 161 | | |
| | 1230 | 162 | | return services; |
| | | 163 | | } |
| | | 164 | | |
| | | 165 | | /// <summary> |
| | | 166 | | /// Gets detailed information about all registered services. |
| | | 167 | | /// </summary> |
| | | 168 | | /// <param name="serviceCollection">The service provider to inspect.</param> |
| | | 169 | | /// <returns>A read-only list of service registration information.</returns> |
| | | 170 | | /// <exception cref="ArgumentNullException">Thrown when serviceCollection is null.</exception> |
| | | 171 | | /// <example> |
| | | 172 | | /// <code> |
| | | 173 | | /// // Get all singleton services |
| | | 174 | | /// var singletons = serviceCollection.GetServiceRegistrations( |
| | | 175 | | /// descriptor => descriptor.Lifetime == ServiceLifetime.Singleton); |
| | | 176 | | /// |
| | | 177 | | /// // Get all services with a specific implementation type |
| | | 178 | | /// var specificImpls = serviceCollection.GetServiceRegistrations( |
| | | 179 | | /// descriptor => descriptor.ImplementationType == typeof(MyService)); |
| | | 180 | | /// </code> |
| | | 181 | | /// </example> |
| | | 182 | | public static IReadOnlyList<ServiceRegistrationInfo> GetServiceRegistrations( |
| | | 183 | | this IServiceCollection serviceCollection) |
| | | 184 | | { |
| | 6 | 185 | | ArgumentNullException.ThrowIfNull(serviceCollection); |
| | | 186 | | |
| | 11 | 187 | | return serviceCollection.GetServiceRegistrations(_ => true); |
| | | 188 | | } |
| | | 189 | | |
| | | 190 | | /// <summary> |
| | | 191 | | /// Gets detailed information about all registered services that match the specified predicate. |
| | | 192 | | /// </summary> |
| | | 193 | | /// <param name="serviceCollection">The service provider to inspect.</param> |
| | | 194 | | /// <param name="predicate">A function to filter the service descriptors.</param> |
| | | 195 | | /// <returns>A read-only list of service registration information.</returns> |
| | | 196 | | /// <exception cref="ArgumentNullException">Thrown when serviceCollection or predicate is null.</exception> |
| | | 197 | | /// <example> |
| | | 198 | | /// <code> |
| | | 199 | | /// // Get all singleton services |
| | | 200 | | /// var singletons = serviceCollection.GetServiceRegistrations( |
| | | 201 | | /// descriptor => descriptor.Lifetime == ServiceLifetime.Singleton); |
| | | 202 | | /// |
| | | 203 | | /// // Get all services with a specific implementation type |
| | | 204 | | /// var specificImpls = serviceCollection.GetServiceRegistrations( |
| | | 205 | | /// descriptor => descriptor.ImplementationType == typeof(MyService)); |
| | | 206 | | /// </code> |
| | | 207 | | /// </example> |
| | | 208 | | public static IReadOnlyList<ServiceRegistrationInfo> GetServiceRegistrations( |
| | | 209 | | this IServiceCollection serviceCollection, |
| | | 210 | | Func<ServiceDescriptor, bool> predicate) |
| | | 211 | | { |
| | 65 | 212 | | ArgumentNullException.ThrowIfNull(serviceCollection); |
| | 64 | 213 | | ArgumentNullException.ThrowIfNull(predicate); |
| | | 214 | | |
| | 63 | 215 | | return serviceCollection |
| | 63 | 216 | | .Where(predicate) |
| | 2349 | 217 | | .Select(descriptor => new ServiceRegistrationInfo(descriptor)) |
| | 63 | 218 | | .ToArray(); |
| | | 219 | | } |
| | | 220 | | |
| | | 221 | | /// <summary> |
| | | 222 | | /// Determines whether a service of the specified type is registered in the service collection. |
| | | 223 | | /// </summary> |
| | | 224 | | /// <typeparam name="TService">The service type to check.</typeparam> |
| | | 225 | | /// <param name="services">The service collection to check.</param> |
| | | 226 | | /// <returns>True if the service is registered; otherwise, false.</returns> |
| | | 227 | | public static bool IsRegistered<TService>(this IServiceCollection services) |
| | | 228 | | { |
| | 5 | 229 | | ArgumentNullException.ThrowIfNull(services); |
| | 4 | 230 | | return services.IsRegistered(typeof(TService)); |
| | | 231 | | } |
| | | 232 | | |
| | | 233 | | /// <summary> |
| | | 234 | | /// Determines whether a service of the specified type is registered in the service collection. |
| | | 235 | | /// </summary> |
| | | 236 | | /// <param name="services">The service collection to check.</param> |
| | | 237 | | /// <param name="serviceType">The service type to check.</param> |
| | | 238 | | /// <returns>True if the service is registered; otherwise, false.</returns> |
| | | 239 | | public static bool IsRegistered( |
| | | 240 | | this IServiceCollection services, |
| | | 241 | | Type serviceType) |
| | | 242 | | { |
| | 12 | 243 | | ArgumentNullException.ThrowIfNull(services); |
| | 23 | 244 | | return services.Any(d => d.ServiceType == serviceType); |
| | | 245 | | } |
| | | 246 | | |
| | | 247 | | private static TService CreateOriginalService<TService>(IServiceProvider provider, ServiceDescriptor originalDescrip |
| | | 248 | | { |
| | 156 | 249 | | if (originalDescriptor.ImplementationFactory is not null) |
| | | 250 | | { |
| | 102 | 251 | | return (TService)originalDescriptor.ImplementationFactory(provider); |
| | | 252 | | } |
| | | 253 | | |
| | 54 | 254 | | if (originalDescriptor.ImplementationInstance is not null) |
| | | 255 | | { |
| | 1 | 256 | | return (TService)originalDescriptor.ImplementationInstance; |
| | | 257 | | } |
| | | 258 | | |
| | 53 | 259 | | if (originalDescriptor.ImplementationType is not null) |
| | | 260 | | { |
| | 53 | 261 | | return (TService)ActivatorUtilities.CreateInstance(provider, originalDescriptor.ImplementationType); |
| | | 262 | | } |
| | | 263 | | |
| | 0 | 264 | | throw new InvalidOperationException($"Unable to create instance of service {typeof(TService).Name} from the orig |
| | | 265 | | } |
| | | 266 | | |
| | | 267 | | private static object CreateOriginalService(IServiceProvider provider, ServiceDescriptor originalDescriptor, Type se |
| | | 268 | | { |
| | 81 | 269 | | if (originalDescriptor.ImplementationFactory is not null) |
| | | 270 | | { |
| | 81 | 271 | | return originalDescriptor.ImplementationFactory(provider); |
| | | 272 | | } |
| | | 273 | | |
| | 0 | 274 | | if (originalDescriptor.ImplementationInstance is not null) |
| | | 275 | | { |
| | 0 | 276 | | return originalDescriptor.ImplementationInstance; |
| | | 277 | | } |
| | | 278 | | |
| | 0 | 279 | | if (originalDescriptor.ImplementationType is not null) |
| | | 280 | | { |
| | 0 | 281 | | return ActivatorUtilities.CreateInstance(provider, originalDescriptor.ImplementationType); |
| | | 282 | | } |
| | | 283 | | |
| | 0 | 284 | | throw new InvalidOperationException($"Unable to create instance of service {serviceType.Name} from the original |
| | | 285 | | } |
| | | 286 | | } |