-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathServiceProviderExtensions.cs
More file actions
46 lines (36 loc) · 1.59 KB
/
ServiceProviderExtensions.cs
File metadata and controls
46 lines (36 loc) · 1.59 KB
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
using System;
using FluentValidation;
namespace SharpGrip.FluentValidation.AutoValidation.Shared.Extensions;
public static class ServiceProviderExtensions
{
public static object? GetValidator(this IServiceProvider serviceProvider, Type type, bool useBaseTypeValidations)
{
var validator = serviceProvider.GetService(typeof(IValidator<>).MakeGenericType(type));
if (validator is not null) return validator;
if (!useBaseTypeValidations) return null;
return GetValidatorFromBaseClasses(serviceProvider, type)
?? GetValidatorFromInterfaces(serviceProvider, type);
}
private static object? GetValidatorFromBaseClasses(IServiceProvider serviceProvider, Type type)
{
var baseType = type.BaseType;
while (baseType is not null && baseType != typeof(object))
{
var baseValidatorType = typeof(IValidator<>).MakeGenericType(baseType);
var baseValidator = serviceProvider.GetService(baseValidatorType);
if (baseValidator is not null) return baseValidator;
baseType = baseType.BaseType;
}
return null;
}
private static object? GetValidatorFromInterfaces(IServiceProvider serviceProvider, Type type)
{
foreach (var interfaceType in type.GetInterfaces())
{
var interfaceValidatorType = typeof(IValidator<>).MakeGenericType(interfaceType);
var interfaceValidator = serviceProvider.GetService(interfaceValidatorType);
if (interfaceValidator is not null) return interfaceValidator;
}
return null;
}
}