2

I am implementing my own user registration service based on the built in RegistrationService, so I have copied most of it including the first few lines below...

        if (EndpointHost.RequestFilters == null
            || !EndpointHost.RequestFilters.Contains(ValidationFilters.RequestFilter)) //Already gets run
            RegistrationValidator.ValidateAndThrow(request, ApplyTo.Post);


        // Above line does not get hit as there is the ValidationFilters.RequestFilter
        //...but then the code should have previously run validation and failed?
        //...Adding the following line causes the validation to run and fail when expected
       //...but I should not required it as that is the point of the global ValidationFilters.RequestFilter??
        RegistrationValidator.ValidateAndThrow(request, ApplyTo.Post);

From what I understand the ValidationFilters.RequestFilter should have been hit earlier and my validation exception thrown.

N.B: I have put this line at the very end of my apphost configuration.

Plugins.Add(new ValidationFeature());

And I am successfully registering my validator, with this:

container.Register<AbstractValidator<UserRegistration>>(new UserRegistrationValidator());

...I have now narrowed it down to the following lines of ServiceStack source code in ValidatorCache.cs

public class ValidatorCache<T>
{
    public static IValidator GetValidator(IHttpRequest httpReq)
    {
        return httpReq.TryResolve<IValidator<T>>();
    }
}

...The TryResolve is not finding the validator.

4

2 回答 2

2

我发现验证器没有从 IOC 容器中解析……我没有深入研究这个问题,而是后退了一步,而是发现了为什么自动注册方法以前对我不起作用。

原因是我原来有这个...

public interface IUserRegistrationValidator : IValidator<UserRegistration>
{
}

public class UserRegistrationValidator : AbstractValidator<UserRegistration>, IUserRegistrationValidator
{ //..etc

由于明显的原因(建议友好的例外),ServiceStack 代码在下面显示的线上跳闸:

    public static void RegisterValidator(this Container container, Type validator, ReuseScope scope=ReuseScope.None)
    {
        var baseType = validator.BaseType;
        while (!baseType.IsGenericType) // WOULD FAIL ON THIS LINE HERE
        {
            baseType = baseType.BaseType;
        }

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

        container.RegisterAutoWiredType(validator, validatorType, scope);
    }

在摆脱了我一直在玩的无意义的接口之后,我可以使用自动注册验证器的方法......例如:

container.RegisterValidators(typeof(UserRegistrationValidator).Assembly);

这解决了我的问题,我不确定如何从https://github.com/ServiceStack/ServiceStack/wiki/Validation手动注册 UserValidator并让它工作,因为我仍然有点印象,以下不会好好工作。

container.Register<AbstractValidator<User>>(new UserValidator());

...我当然可能错了!

于 2013-09-10T14:21:14.660 回答
1

您是否考虑过在 中注册验证器AppHost.cs

// This method scans the assembly for validators
container.RegisterValidators(Assemblies);
于 2013-09-05T03:05:05.767 回答