| | | 1 | | using Microsoft.Extensions.DependencyInjection; |
| | | 2 | | |
| | | 3 | | using System.Text; |
| | | 4 | | |
| | | 5 | | namespace NexusLabs.Needlr; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Represents a lifetime mismatch where a longer-lived service depends on a shorter-lived service. |
| | | 9 | | /// This is also known as a "captive dependency" and can lead to unexpected behavior. |
| | | 10 | | /// </summary> |
| | | 11 | | /// <param name="ConsumerServiceType">The service type that has the dependency.</param> |
| | | 12 | | /// <param name="ConsumerImplementationType">The implementation type that has the dependency.</param> |
| | | 13 | | /// <param name="ConsumerLifetime">The lifetime of the consumer service.</param> |
| | | 14 | | /// <param name="DependencyServiceType">The service type being depended upon.</param> |
| | | 15 | | /// <param name="DependencyLifetime">The lifetime of the dependency.</param> |
| | 19 | 16 | | public sealed record LifetimeMismatch( |
| | 49 | 17 | | Type ConsumerServiceType, |
| | 12 | 18 | | Type? ConsumerImplementationType, |
| | 48 | 19 | | ServiceLifetime ConsumerLifetime, |
| | 49 | 20 | | Type DependencyServiceType, |
| | 67 | 21 | | ServiceLifetime DependencyLifetime) |
| | | 22 | | { |
| | | 23 | | /// <summary> |
| | | 24 | | /// Returns a detailed, formatted string representation of this mismatch |
| | | 25 | | /// suitable for debugging and diagnostics. |
| | | 26 | | /// </summary> |
| | | 27 | | public string ToDetailedString() |
| | | 28 | | { |
| | 12 | 29 | | var sb = new StringBuilder(); |
| | 12 | 30 | | var consumerName = ConsumerImplementationType?.Name ?? ConsumerServiceType.Name; |
| | | 31 | | |
| | 12 | 32 | | sb.AppendLine($"┌─ Lifetime Mismatch"); |
| | 12 | 33 | | sb.AppendLine($"│ {ConsumerServiceType.Name} ({ConsumerLifetime})"); |
| | 12 | 34 | | sb.AppendLine($"│ └─ depends on ─▶ {DependencyServiceType.Name} ({DependencyLifetime})"); |
| | 12 | 35 | | sb.AppendLine($"│"); |
| | 12 | 36 | | sb.AppendLine($"│ Problem: {ConsumerLifetime} service will capture {DependencyLifetime} dependency"); |
| | 12 | 37 | | sb.AppendLine($"│ Fix: Change {ConsumerServiceType.Name} to {DependencyLifetime},"); |
| | 12 | 38 | | sb.AppendLine($"│ or change {DependencyServiceType.Name} to {ConsumerLifetime},"); |
| | 12 | 39 | | sb.AppendLine($"│ or inject IServiceScopeFactory instead."); |
| | 12 | 40 | | sb.Append($"└─"); |
| | | 41 | | |
| | 12 | 42 | | return sb.ToString(); |
| | | 43 | | } |
| | | 44 | | } |