Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deprecation of AbstractValidator.EnsureInstanceNotNull #2069

Closed
JeremySkinner opened this issue Feb 19, 2023 · 0 comments
Closed

Deprecation of AbstractValidator.EnsureInstanceNotNull #2069

JeremySkinner opened this issue Feb 19, 2023 · 0 comments

Comments

@JeremySkinner
Copy link
Member

JeremySkinner commented Feb 19, 2023

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.

@FluentValidation FluentValidation locked as resolved and limited conversation to collaborators Feb 19, 2023
@JeremySkinner JeremySkinner changed the title Deprecation of AbstractValidator.EnsureInstanceNotNull in 12.0 Deprecation of AbstractValidator.EnsureInstanceNotNull Feb 20, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant