Am I misusing validation feature? (i.e. autowired validators were not designed to be used for application logic checks)
I would say this is best done in the business logic away from the validation, because checking for a uniqueness is actually a verification check rather than validation, because it requires checking against a data source. My answer on this question addresses a similar concern.
While you can override the response status code of the validation error using the ErrorResponseFilter
, I would recommend creating your own request filter for this business logic, as overriding the response there will be messy as your application grows, and again, it's not really validation.
Using a filter attribute is straightforward in ServiceStack:
public class VerifySomethingCodeAttribute : Attribute, IHasRequestFilter
{
IHasRequestFilter IHasRequestFilter.Copy()
{
return this;
}
public int Priority { get { return int.MinValue; } }
public void RequestFilter(IRequest req, IResponse res, object requestDto)
{
SomethingRequest somethingRequestDto = requestDto as SomethingRequest;
if(somethingRequestDto == null)
return;
// Verify the code
// Replace with suitable logic
// If you need the database your wire it up from the IoC
// i.e. HostContext.TryResolve<IDbConnectionFactory>();
bool isUnique = ...
if(!isUnique)
throw HttpError.Conflict("This record already exists");
}
}
Then simply annotate the DTO:
[VerifySomethingCode]
public class SomethingRequest {
public string Code { get; set; }
}
Then you can be sure that the Code in the DTO will have been verified as unique and you can return any status and response you want. The filter gives you total control.
Hope this helps.