2

我有一个 FluentValidation 验证器,我想用它来验证预订。在预订时,您必须选择在您选择的旅行中作为可用房型存在的房型。我需要从服务中获取可用的房间类型,并传入游览代码。处理在需要的地方获取旅游代码的最佳方法是什么?

到目前为止我得到了什么:

public class BookingValidator : AbstractValidator<Booking>, IBookingValidator

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

public class RoomValidator : AbstractValidator<Room>

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

解决问题的一些技巧:

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()??

}

所以主要问题是如何或在哪里将旅游代码放入验证器......?

4

1 回答 1

2

我建议创建一个依赖于 IRoomTypeService 和 IBookingValidator 的服务。它从 IRoomTypeService 依赖项中获取可用的房间类型,并通过属性将它们传递给验证器。通过示例查看以下代码:

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);
    }
}
于 2010-07-23T12:38:54.580 回答