| | | 1 | | using Microsoft.Extensions.DependencyInjection; |
| | | 2 | | |
| | | 3 | | using System.Diagnostics.CodeAnalysis; |
| | | 4 | | using System.Reflection; |
| | | 5 | | |
| | | 6 | | namespace NexusLabs.Needlr; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Extension methods for detecting lifetime mismatches (captive dependencies) in service registrations. |
| | | 10 | | /// </summary> |
| | | 11 | | public static class LifetimeMismatchExtensions |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Detects lifetime mismatches (captive dependencies) in the service collection. |
| | | 15 | | /// A lifetime mismatch occurs when a longer-lived service depends on a shorter-lived service. |
| | | 16 | | /// </summary> |
| | | 17 | | /// <param name="services">The service collection to analyze.</param> |
| | | 18 | | /// <returns>A list of detected lifetime mismatches.</returns> |
| | | 19 | | /// <exception cref="ArgumentNullException">Thrown when services is null.</exception> |
| | | 20 | | /// <remarks> |
| | | 21 | | /// <para>Lifetime hierarchy (from longest to shortest):</para> |
| | | 22 | | /// <list type="bullet"> |
| | | 23 | | /// <item>Singleton (lives for entire application lifetime)</item> |
| | | 24 | | /// <item>Scoped (lives for the scope/request lifetime)</item> |
| | | 25 | | /// <item>Transient (new instance every time)</item> |
| | | 26 | | /// </list> |
| | | 27 | | /// <para> |
| | | 28 | | /// A mismatch occurs when a service with a longer lifetime depends on a service with a shorter lifetime. |
| | | 29 | | /// For example, a Singleton depending on a Scoped service will "capture" the scoped instance, |
| | | 30 | | /// causing it to live longer than intended. |
| | | 31 | | /// </para> |
| | | 32 | | /// <para> |
| | | 33 | | /// Factory registrations cannot be analyzed and are skipped. |
| | | 34 | | /// </para> |
| | | 35 | | /// </remarks> |
| | | 36 | | public static IReadOnlyList<LifetimeMismatch> DetectLifetimeMismatches(this IServiceCollection services) |
| | | 37 | | { |
| | 512 | 38 | | ArgumentNullException.ThrowIfNull(services); |
| | | 39 | | |
| | 511 | 40 | | var mismatches = new List<LifetimeMismatch>(); |
| | | 41 | | |
| | | 42 | | // Build a lookup of service type -> lifetime |
| | 511 | 43 | | var lifetimeLookup = BuildLifetimeLookup(services); |
| | | 44 | | |
| | 268206 | 45 | | foreach (var descriptor in services) |
| | | 46 | | { |
| | | 47 | | // Skip factory registrations - we can't analyze their dependencies |
| | 133592 | 48 | | if (descriptor.ImplementationType is null) |
| | | 49 | | { |
| | | 50 | | continue; |
| | | 51 | | } |
| | | 52 | | |
| | 45675 | 53 | | var consumerLifetime = descriptor.Lifetime; |
| | | 54 | | |
| | | 55 | | // Transient services can depend on anything without causing captive dependencies |
| | 45675 | 56 | | if (consumerLifetime == ServiceLifetime.Transient) |
| | | 57 | | { |
| | | 58 | | continue; |
| | | 59 | | } |
| | | 60 | | |
| | | 61 | | // Analyze constructor dependencies |
| | | 62 | | // Note: descriptor.ImplementationType from MS.DI doesn't have DynamicallyAccessedMembers annotation, |
| | | 63 | | // but constructor metadata is typically preserved for DI-registered types. |
| | | 64 | | #pragma warning disable IL2072 // Target parameter argument does not satisfy 'DynamicallyAccessedMembersAttribute' in ca |
| | 43624 | 65 | | var dependencies = GetConstructorDependencies(descriptor.ImplementationType); |
| | | 66 | | #pragma warning restore IL2072 |
| | | 67 | | |
| | 123358 | 68 | | foreach (var dependencyType in dependencies) |
| | | 69 | | { |
| | 18055 | 70 | | if (!lifetimeLookup.TryGetValue(dependencyType, out var dependencyLifetime)) |
| | | 71 | | { |
| | | 72 | | // Dependency not registered - skip |
| | | 73 | | continue; |
| | | 74 | | } |
| | | 75 | | |
| | 14025 | 76 | | if (IsLifetimeMismatch(consumerLifetime, dependencyLifetime)) |
| | | 77 | | { |
| | 18 | 78 | | mismatches.Add(new LifetimeMismatch( |
| | 18 | 79 | | ConsumerServiceType: descriptor.ServiceType, |
| | 18 | 80 | | ConsumerImplementationType: descriptor.ImplementationType, |
| | 18 | 81 | | ConsumerLifetime: consumerLifetime, |
| | 18 | 82 | | DependencyServiceType: dependencyType, |
| | 18 | 83 | | DependencyLifetime: dependencyLifetime)); |
| | | 84 | | } |
| | | 85 | | } |
| | | 86 | | } |
| | | 87 | | |
| | 511 | 88 | | return mismatches; |
| | | 89 | | } |
| | | 90 | | |
| | | 91 | | private static Dictionary<Type, ServiceLifetime> BuildLifetimeLookup(IServiceCollection services) |
| | | 92 | | { |
| | 511 | 93 | | var lookup = new Dictionary<Type, ServiceLifetime>(); |
| | | 94 | | |
| | 268206 | 95 | | foreach (var descriptor in services) |
| | | 96 | | { |
| | | 97 | | // Use the last registration for a given service type (mimics DI container behavior) |
| | 133592 | 98 | | lookup[descriptor.ServiceType] = descriptor.Lifetime; |
| | | 99 | | } |
| | | 100 | | |
| | 511 | 101 | | return lookup; |
| | | 102 | | } |
| | | 103 | | |
| | | 104 | | private static IEnumerable<Type> GetConstructorDependencies( |
| | | 105 | | [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) |
| | | 106 | | { |
| | | 107 | | // Get the constructor that the DI container would use (longest parameter list) |
| | 43624 | 108 | | var constructors = implementationType.GetConstructors(BindingFlags.Public | BindingFlags.Instance); |
| | | 109 | | |
| | 43624 | 110 | | if (constructors.Length == 0) |
| | | 111 | | { |
| | 0 | 112 | | yield break; |
| | | 113 | | } |
| | | 114 | | |
| | | 115 | | // DI container typically uses the constructor with the most parameters |
| | 43624 | 116 | | var constructor = constructors |
| | 43624 | 117 | | .OrderByDescending(c => c.GetParameters().Length) |
| | 43624 | 118 | | .First(); |
| | | 119 | | |
| | 123358 | 120 | | foreach (var parameter in constructor.GetParameters()) |
| | | 121 | | { |
| | 18055 | 122 | | yield return parameter.ParameterType; |
| | | 123 | | } |
| | 43624 | 124 | | } |
| | | 125 | | |
| | | 126 | | /// <summary> |
| | | 127 | | /// Determines if there is a lifetime mismatch between a consumer and its dependency. |
| | | 128 | | /// </summary> |
| | | 129 | | /// <param name="consumerLifetime">The lifetime of the consuming service.</param> |
| | | 130 | | /// <param name="dependencyLifetime">The lifetime of the dependency.</param> |
| | | 131 | | /// <returns>True if there is a mismatch (consumer lives longer than dependency).</returns> |
| | | 132 | | private static bool IsLifetimeMismatch(ServiceLifetime consumerLifetime, ServiceLifetime dependencyLifetime) |
| | | 133 | | { |
| | | 134 | | // Lifetime "rank" - higher number = longer lifetime |
| | 28050 | 135 | | static int GetLifetimeRank(ServiceLifetime lifetime) => lifetime switch |
| | 28050 | 136 | | { |
| | 6 | 137 | | ServiceLifetime.Transient => 0, |
| | 18 | 138 | | ServiceLifetime.Scoped => 1, |
| | 28026 | 139 | | ServiceLifetime.Singleton => 2, |
| | 0 | 140 | | _ => 0 |
| | 28050 | 141 | | }; |
| | | 142 | | |
| | 14025 | 143 | | var consumerRank = GetLifetimeRank(consumerLifetime); |
| | 14025 | 144 | | var dependencyRank = GetLifetimeRank(dependencyLifetime); |
| | | 145 | | |
| | | 146 | | // Mismatch if consumer lives longer than dependency |
| | 14025 | 147 | | return consumerRank > dependencyRank; |
| | | 148 | | } |
| | | 149 | | } |