MediatR – Can not create new Instance of TResponse

I am trying to create a new PipelineBehavior that returns a new Instance of TResponse.

With this code if I put a break point to the "handle" I can see that the pipeline works.

  public class ValidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
        where TRequest : IRequest<TResponse>
        where TResponse : Response
    {
        private readonly ILogger<ValidationBehaviour<TRequest, TResponse>> _logger;
        private readonly IValidationHandler<TRequest> _validationHandler;
    
        public ValidationBehaviour(ILogger<ValidationBehaviour<TRequest, TResponse>> logger)
        {
            this._logger = logger;
        }
    
        public ValidationBehaviour(ILogger<ValidationBehaviour<TRequest, TResponse>> logger, IValidationHandler<TRequest> validationHandler)
        {
            this._logger = logger;
            this._validationHandler = validationHandler;
        }
    
        public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
        {
            var requestName = request.GetType();
            _logger.LogInformation("{Request} does not have a validation handler configured.", requestName);
            return await next();
        }
    }

but I can't have this syntax

return new TResponse { StatusCode = (int)HttpStatusCode.BadRequest, SFADevErrorMessage = result.Error };

I have seen examples where they use the "new()" keyword in the constraint and that allows them to create a new Instance of TResponse. Like that.

public class ValidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
    where TResponse : Response, new()

If I do the same I am able to do that new TResponse { StatusCode = (int)HttpStatusCode.BadRequest, SFADevErrorMessage = result.Error };

but then my pipeline is not working - is not executing and the executable code never hits my break point.

Any idea why this is happening? Am I missing something?



Read more here: https://stackoverflow.com/questions/67013080/mediatr-can-not-create-new-instance-of-tresponse

Content Attribution

This content was originally published by Thomas K at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: