AspNetCore Mvc Validation in ServiceStackController

I have migrated a .Net 4.6.1 Mvc Website to Asp.Net.Core.

I have defined validators for my models using ServiceStack.FluentValidation.

In the .Net 4.6.1 wesbite the ModelState validation uses these validators by populating the ModelState.

In AspNetCore this is nog longer the case. I was checking out ServiceStack Mvc Core sample but there was no example of validation.

Could you please tell me how to inject my validators in the ServiceStackControllers?

The package FluentValidation.AspNetCore has a option like this:

services.AddMvc(setup => {
  //...mvc setup...
}).AddFluentValidation();

May be a solution like this could be implemented for ServiceStack.FluentValidation as well?

It’s not really possible as the Services needs to be configured before ServiceStack AppHost exists. The best way to access the ServiceStack validators is from:

var validator = HostContext.TryResolve<IValidator<MyType>>();

Although I’d personally just use MVC FluentValidation in MVC and ServiceStack FluentValidation for ServiceStack Services.

FYI, if you want you can try registering ServiceStack validators in .NET Core IOC with:

public static class AppExtensions
{
    public static IServiceCollection AddServiceStackValidators(this IServiceCollection services,
        params Assembly[] assemblies)
    {
        foreach (var assembly in assemblies)
        {
            foreach (var validator in assembly.GetTypes()
                .Where(t => t.IsOrHasGenericInterfaceTypeOf(typeof(IValidator<>))))
            {
                services.AddServiceStackValidator(validator);
            }
        }
        return services;
    }

    public static IServiceCollection AddServiceStackValidator(this IServiceCollection services, Type validator)
    {
        var baseType = validator.BaseType;
        if (validator.IsInterface || baseType == null)
            return services;

        while (baseType != null && !baseType.IsGenericType)
        {
            baseType = baseType.BaseType;
        }

        if (baseType == null)
            return services;

        var dtoType = baseType.GetGenericArguments()[0];
        var validatorType = typeof(IValidator<>).GetCachedGenericType(dtoType);

        services.AddTransient(validatorType);
        return services;
    }
}

A couple of caveats: .NET Core’s IOC doesn’t support property injection so any dependencies your validators need would be injected in the constructor and you’ll need to inject the Request for Validators that use it, e.g:

_validator.Request = base.ServiceStackRequest;

Thanks for your answers.It saves me hours of investigating.