Skip to content

Commit

Permalink
Improved validators scan using IValidator interface (#39)
Browse files Browse the repository at this point in the history
* Better validators scan
* Considering lazy loading
  • Loading branch information
GioviQ authored Sep 21, 2020
1 parent 7fda94c commit cd0e981
Showing 1 changed file with 19 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,21 @@
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using static FluentValidation.AssemblyScanner;

namespace Blazored.FluentValidation
{
public static class EditContextFluentValidationExtensions
{
private readonly static char[] separators = new[] { '.', '[' };

private static List<string> scannedAssembly = new List<string>();

private static List<AssemblyScanResult> assemblyScanResults = new List<AssemblyScanResult>();

public static EditContext AddFluentValidation(this EditContext editContext, IServiceProvider serviceProvider, bool disableAssemblyScanning, IValidator validator)
{
if (editContext == null)
Expand Down Expand Up @@ -94,19 +100,24 @@ private static IValidator GetValidatorForModel(IServiceProvider serviceProvider,
return null;
}

var abstractValidatorType = typeof(AbstractValidator<>).MakeGenericType(model.GetType());

Type modelValidatorType = null;
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(i => !scannedAssembly.Contains(i.FullName)))
{
modelValidatorType = IgnoreErrors<Type>(() => assembly.GetTypes().FirstOrDefault(t => t.IsSubclassOf(abstractValidatorType)));

if (modelValidatorType is object && modelValidatorType != default)
try
{
assemblyScanResults.AddRange(FindValidatorsInAssembly(assembly));
}
catch (Exception)
{
break;
}

scannedAssembly.Add(assembly.FullName);
}


var interfaceValidatorType = typeof(IValidator<>).MakeGenericType(model.GetType());

Type modelValidatorType = assemblyScanResults.FirstOrDefault(i => interfaceValidatorType.IsAssignableFrom(i.InterfaceType))?.ValidatorType;

if (modelValidatorType == null)
{
return null;
Expand Down

0 comments on commit cd0e981

Please sign in to comment.