vonec
vonec

Reputation: 701

ServiceStack Validator - Request not injected

I have a validator and I'm trying to use some session variables as part of the validation logic, however the base.Request is always coming back as NULL. I've added it in the lambda function as directed and also the documentation for Validation seems to be out of date as the tip in the Fluent validation for request dtos section mentions to use IRequiresHttpRequest, but the AbstractValidator class already implements IRequiresRequest.

This is my code:

public class UpdateContact : IReturn<UpdateContactResponse>
{
    public Guid Id { get; set; }

    public string Reference { get; set; }

    public string Notes { get; set; }

    public List<Accounts> Accounts { get; set; }
}

public class UpdateContactResponse : ResponseBase
{
    public Guid ContactId { get; set; }
}

public class UpdateContactValidator : AbstractValidator<UpdateContact>
{
    public UpdateContactValidator(IValidator<AccountDetail> accountDetailValidator)
    {
        RuleSet(ApplyTo.Post | ApplyTo.Put, () => {
            var session = base.Request.GetSession() as CustomAuthSession;
            RuleFor(c => c.Reference).Must(x => !string.IsNullOrEmpty(x) && session.Region.GetCountry() == RegionCodes.AU);
        });

        RuleFor(R => R.Accounts).SetCollectionValidator(accountDetailValidator);
    }
}

Is there something I'm missing?

Upvotes: 4

Views: 195

Answers (1)

mythz
mythz

Reputation: 143319

Access to injected dependencies can only be done from within a RuleFor() lambda, delegates in a RuleSet() are executed on constructor initialization to setup the rules for that RuleSet.

So you need to change your access to base.Request to within RuleFor() lambda:

RuleSet(ApplyTo.Post | ApplyTo.Put, () => {
  RuleFor(c => c.Reference)
    .Must(x => !string.IsNullOrEmpty(x) && 
    (Request.GetSession() as CustomAuthSession).Region.GetCountry() == RegionCodes.AU);
});

Upvotes: 4

Related Questions