Skip to content

Deprecation of AbstractValidator.EnsureInstanceNotNull #2069

@JeremySkinner

Description

@JeremySkinner

Summary

The EnsureInstanceNotNull method is being deprecated in FluentValidation 11.5.x and removed from 12.0

Background

FluentValidations is a library for validating the properties of objects and as such, the root model being validated must be non-null. By default, if you pass a null root instance into a validator's Validate method then FluentValidation will throw an exception indicating that null cannot be passed to Validate.

This behaviour exists to prevent NullReferenceExceptions being thrown within your rule definitions.

(Note that this behaviour only occurs for the root model, child validators for null nested models will simply be skipped if their instance is null.)

However, this mechanism can be disabled by overriding the undocumented EnsureInstanceNotNull method in your validator. This will prevent FluentValidation from throwing an exception if the root instance is null.

New Behaviour

Going forward, we will no longer support disabling this behaviour - the root instance being validated must always be non-null. As such the ability to override the EnsureInstanceNotNull method is deprecated in 11.x and will be removed in 12.0.

If your root model might be null, then you should check this before invoking your validator.

Alternatively, if you want to generate a validation failure if the root model is null you can do so by overriding the PreValidate method in your validator and generate a validation failure:

protected override bool PreValidate(ValidationContext<Person> context, ValidationResult result) 
{
	if (context.InstanceToValidate == null) 
	{
		context.AddFailure(string.Empty, "A non-null instance must be passed to the validator");
		return false;
	}

	return true;
}

This will generate a single validation failure if the root model is null and prevent execution of any other rules.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions