I have the following method that takes in a details object, validates it, converts it to a request and enqueues it. Everything is fine apart from the validate request which I am having trouble with. Basically, there is different validation logic for each different details object. I know from the generic constraint that the details object must have a base class of BaseDetails and from the actual generic parameter I know the exact derived type, but do not know how to use these to write my validator class so it handles all types of details:
private void Enqueue<TDetails, TRequest>(TDetails details)
where TDetails: BaseDetails where TRequest: BaseRequest
{
bool isValid = _validator.Validate(details);
if (isValid)
{
TRequest request = ObjectMapper
.CreateMappedMessage<TDetails, TRequest>(details);
_queue.Enqueue(request);
}
}
I think you need to create a validator class for each implementation of TDetails which knows how to validate that particular implementation, then have a factory to produce the right validator for a given TDetails implementation and have your _validator get the correct class for doing the work from the factory and get the class to do the validation.
Obviously you could have some of the common validation in a base class.
You might be better having the validation on the object itself though rather than create a separate validator for each TDetails implementation…