-
Notifications
You must be signed in to change notification settings - Fork 21
/
ServiceCollectionExtensions.cs
79 lines (67 loc) · 2.7 KB
/
ServiceCollectionExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System.Text;
using Microsoft.Extensions.DependencyInjection;
namespace ServiceCollectionVerify;
public class VerifyResult
{
public bool IsValid => Errors.Count == 0;
public List<string> Errors { get; } = new();
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine($"Found {Errors.Count} error(s):");
for (var i = 0; i < Errors.Count; i++)
{
sb.AppendLine($"{i + 1}. {Errors[i]}");
}
return sb.ToString();
}
}
public static class ServiceCollectionExtensions
{
public static void Verify(this IServiceCollection services)
{
var result = new VerifyResult();
using var serviceProvider = services.BuildServiceProvider();
result.Errors.AddRange(CheckServicesCanBeResolved(serviceProvider, services));
result.Errors.AddRange(CheckForCaptiveDependencies(services));
if (!result.IsValid)
{
throw new InvalidOperationException(result.ToString());
}
}
private static List<string> CheckServicesCanBeResolved(IServiceProvider serviceProvider, IServiceCollection services)
{
var unresolvedTypes = new List<string>();
foreach (var serviceDescriptor in services)
{
try
{
serviceProvider.GetRequiredService(serviceDescriptor.ServiceType);
}
catch
{
unresolvedTypes.Add($"Unable to resolve '{serviceDescriptor.ServiceType.FullName}'");
}
}
return unresolvedTypes;
}
private static IEnumerable<string> CheckForCaptiveDependencies(IServiceCollection services)
{
var singletonServices = services
.Where(descriptor => descriptor.Lifetime == ServiceLifetime.Singleton)
.Select(descriptor => descriptor.ServiceType);
foreach (var singletonService in singletonServices)
{
var captiveScopedServices = singletonService
.GetConstructors()
.SelectMany(property => property.GetParameters())
.Where(propertyType => services.Any(descriptor => descriptor.ServiceType == propertyType.ParameterType
&& descriptor.Lifetime == ServiceLifetime.Scoped
|| descriptor.Lifetime == ServiceLifetime.Transient));
foreach (var captiveService in captiveScopedServices)
{
yield return $"Singleton service '{singletonService.FullName}' has one or more captive dependencies: {string.Join(", ", captiveService.ParameterType.FullName)}";
}
}
}
}