开发者

FluentValidation Validator using arguments

I have a FluentValidation validator that I want to use to validate a booking. On a booking you must choose a room type that exists as an available room type on the tour that you are choosing. I need to get the available room types from a service, passing in the code for the tour. What is the best way to handle getting the tour code where it needs to be?

What I've got so far:

public class BookingValidator : AbstractValidator<Booking>, IBookingValidator

public BookingValidator()
{
    RuleFor(booking => booking.Rooms).SetValidator(new RoomValidator())
}

public class RoomValidator : Abst开发者_运维问答ractValidator<Room>

public RoomValidator()
{
    //validate that room.Type (eg. TWIN) exists in availableRoomTypes (eg List<string> {'SINGLE','TWIN'}
}

Some hack at the problem:

public class BookingValidator : AbstractValidator<Booking>

//should/can i pass in arguments here when IoC container is wiring up IBookingValidator to BookingValidator? Seems awkward
public BookingValidator(string tourCode)
{

//if so, use argument to get available room types, pass to RoomValidator
var availableRooms = RoomTypeService.GetAvailableRoomTypesForTour(tourCode);

RuleFor(booking => booking.Rooms).SetValidator(new RoomValidator(availableRooms))

//alternatively, tourCode is available from booking - is there some way to pass it to RoomValidator?
RuleFor(booking => booking.Rooms).SetValidator(new RoomValidator(),booking => booking.TourCode);

//Or is there some way I should be using .Must() or Custom()??

}

So the main problem is how or where to get tour code into the validator...?


I would suggest creating a service that has dependencies on IRoomTypeService and IBookingValidator. It gets the available room types from the IRoomTypeService dependency and passes them to the validator via a property. See the following code by way of example:

public class BookingValidationService : IBookingValidationService
{
    public IRoomTypeService RoomTypeService { get; set; }

    public IBookingValidator BookingValidator { get; set; }

    public ValidationResult ValidateBooking(Booking booking, string tourCode)
    {
        BookingValidator.AvailableRooms = RoomTypeService.GetAvailableRoomTypesForTour(tourCode);

        return BookingValidator.Validate(booking);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜