'Handling non-nullable reference types and validation

I have an application with non-nullable reference types enabled and am using a mediator pattern.

In the following scenario I'm trying to create a TodoItem. I have a validator that ensures that the Title property of CreateTodoItemCommand is not empty however, the CreateTodoItemCommandHandler has no knowledge of this and so I get a compile time error that I'm referencing a potentially nullable property. I can silence this by using the null-forgiving operator var todoItem = new TodoItem(request.Title!); but this feels a bit like a hack. How are others working around these issues?

public class CreateTodoItemCommand : IRequest<int>
{
    // bound via a web request so can come through as null
    public string? Title { get; set; }
}

public class CreateTodoItemCommandValidator : AbstractValidator<CreateTodoItemCommand>
{
    public CreateTodoItemCommandValidator()
    {
        RuleFor(v => v.Title)
            .MaximumLength(200)
            .NotEmpty();
    }
}

public class CreateTodoItemCommandHandler : IRequestHandler<CreateTodoItemCommand, int>
{
    public async Task<int> Handle(CreateTodoItemCommand request, CancellationToken cancellationToken)
    {
        // [CS8604] Possible null reference argument for parameter 'title' in 'TodoItem(string title)'.
        var todoItem = new Todo(request.Title);

        // omitted
    }
}

public class Todo
{
    public Todo(string title)
    {
       
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source