FluentValidation: BUG: Mvc6 + AutoFac

IMO dependency injection via ctor is fine (better), but I did also some experiments with property setting.

Got 2 FV related issues:

  1. the OnActivating event was raised always after the resolved object was used within IValidator<T>
  2. when I was trying SingleInstance, only the 1st call triggered validation

No1. The issue is FV and architecture related. If I do add a constructor to the validator and reference there a differrent validator, then that 2nd validator gets resolved, and the OnActivating event on that second validator get’s called… so this is fine: public EmployeeDetailsDtoValidator(IValidator<EmployeeAddressDto> employeeAddressDtoValidator, IValidatorFactory f)

But the behavior, when the main IValidator<> is resolved via attribute (FVs MVC infrastructure) is differrent.

No2. I can understand that validators for some reasons must exist per UC. If so, I do really miss this kinda of information from the documentation.

Some samples:

Classic registration:

services.AddMvc().AddFluentValidation(fv => { fv.ValidatorFactoryType = typeof(AttributedValidatorFactory); });

Then separate (manual) registration with property setter, so if IValidator<T> has an IHasFactoryProperty interface, then Factory property will be set, thus allowing to access other objects…

builder
	.RegisterAssemblyTypes(validationAssemblies)
	.Where(t => t.IsClosedTypeOf(typeof(IValidator<>)))
	.AsImplementedInterfaces()
	.OnActivating(e =>
		{
			if (e.Instance is IHasFactoryProperty)
				(e.Instance as IHasFactoryProperty).Factory = e.Context.Resolve<IValidatorFactory>();
		})
	.InstancePerLifetimeScope();

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 23 (11 by maintainers)

Most upvoted comments

@JeremySkinner Just integrated it in the upcoming version of nopCommerce (https://github.com/nopSolutions/nopCommerce/commit/1f3b2f0935a76cd0c8ce81585430e7b1b527d241). Everything works fine. Thanks again!