Reputation: 331
My question is - is it possible and if it is - how, to resolve interface in ServiceStack request filter that uses generic type and the type is retrieved dynamically from DTO of request. The idea is that I have multiple validators defined in my assembly and they use interface that has a generic type. Example:
AddressSaveValidator : BaseValidator<AddressSaveRequest>;
My goal is to on request resolve and see if request has a validator that is defined for such request, then validate and then log the results. The only problem is that I don't know how to resolve interface with generic type. This is example of how would I use it:
RequestFilters.Add((req, res, dto) =>
{
var validator = container.Resolve<IValidator<typeof(dto)>>();
var validatorResult = validator.Validate(dto);
if(validatorResult.IsValid)
{
var logger = container.Resolve<ILogger>();
var result = logger.LogValidationResults(validationResult);
throw ValidationException(result);
}
});
Of course, it does not work.
Upvotes: 2
Views: 306
Reputation: 143319
You can resolve the IValidator
for a request with ValidatorCache.GetValidator()
but you can't throw an Exception in GlobalRequestFilters you'll need to write the Error directly to the response, e.g:
var validator = ValidatorCache.GetValidator(req, dto.GetType());
using (validator as IDisposable)
{
var validatorResult = validator.Validate(dto);
if (validatorResult.IsValid) return;
var errorResponse = DtoUtils.CreateErrorResponse(dto, validatorResult.ToErrorResult());
res.WriteToResponse(req, errorResponse);
}
Upvotes: 2