question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Constraint Violated Exception on MediatR Behavior

See original GitHub issue

I have the following classes:

public class GetPostsRequest : IRequest<Envelope<GetPostsResponse>> {
  public Int32 Age { get; set; }
}

public class GetPostsResponse {
  public String Code { get; set; }
  public String Name { get; set; }      
}

Where Envelope is a wrapper class:

public class Envelope<T> {
  public List<T> Result { get; private set; } = new List<T>();  
  public List<Error> Errors { get; private set; } = new List<Error>();
}

Then I created a ValidationBehavior using FluentValidation:

public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, Envelope<TResponse>> where TRequest : IRequest<Envelope<TResponse>> {

  private readonly IEnumerable<IValidator<TRequest>> _validators;

  public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators) {
    _validators = validators;
  }

  public Task<Envelope<TResponse>> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<Envelope<TResponse>> next) {

    ValidationContext context = new ValidationContext(request);

    List<Error> errors = _validators
      .Select(x => x.Validate(context))
      .SelectMany(x => x.Errors)
      .Select(x => new Error(ErrorCode.DataNotValid, x.ErrorMessage, x.PropertyName))
      .ToList();

    if (errors.Any())
      return Task.FromResult<Envelope<TResponse>>(new Envelope<TResponse>(errors));  

    return next();

  }

}

And I registered the ValidationBehavior on the ASP.NET Core application:

services.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));

When I call the API I get the following error:

An unhandled exception has occurred while executing the request.
System.ArgumentException: GenericArguments[0], 'TRequest', on 'ValidationBehavior`2[TRequest,TResponse]' violates the constraint of type 'TRequest'. 
---> System.TypeLoadException: GenericArguments[0], 'TRequest', on 'ValidationBehavior`2[TRequest,TResponse]' violates the constraint of type parameter 'TRequest'.

Am I missing something?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

5reactions
jbogardcommented, Aug 29, 2018

ASP.NET Core DI does not support constrained open generics. I’ve opened a PR to add support:

https://github.com/aspnet/DependencyInjection/pull/635

In the meantime, you’ll have to switch to one of the 8-9 other containers that do support this feature:

https://github.com/jbogard/MediatR/wiki/Container-Feature-Support

The only containers that don’t support this are Ninject (dead) and MS.Extensions.DI (alive).

0reactions
MisinformedDNAcommented, Jun 5, 2023

FYI: Jimmy pushed through a fix for .NET DI.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Constraint Violated Exception on MediatR Behavior
An unhandled exception has occurred while executing the request. System.ArgumentException: GenericArguments[0], 'TRequest', on ' ...
Read more >
Constraint Violated Exception on MediatR Behavior-.net-core
This means that in your generic implementation, TRequest will be Request , and TResponse will be Envelope<Response> . This however means that the...
Read more >
[Fix]-Constraint Violated Exception on MediatR Behavior
This means that in your generic implementation, TRequest will be Request , and TResponse will be Envelope<Response> . This however means that the...
Read more >
Validation without Exceptions using a MediatR Pipeline ...
This post will focus on validation in a Mediatr Pipeline behaviour. You may find a lot of code like this on StackOverflow, where...
Read more >
The Commercial Mediator's Handbook - Google Books Result
... went on to add that: Culpability here means wholly unreasonable behaviour. ... as an unacceptable constraint on the right of access to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found