6

我有一个使用流利验证和 ninject 的 ASP.NET MVC3 网站设置。验证码有效。但是,我在验证类构造函数中设置了一个断点,我注意到当我请求使用验证的视图时,构造函数会被多次命中。基于非常基本的测试,构造函数被命中的次数似乎等于对象上存在的属性数。有没有其他人遇到过类似的事情?或者有人可以更深入地了解这种类型的验证是如何在幕后工作的?-谢谢

这是构造函数...

public class PersonValidator : AbstractValidator<Person> {
    public PersonValidator() {
        RuleFor(x => x.Id).NotNull();
        RuleFor(x => x.Name).Length(0, 10);
        RuleFor(x => x.Email).EmailAddress();
        RuleFor(x => x.Age).InclusiveBetween(18, 60);
    }
}

这是我正在使用的库/资源(我刚刚获得了 NuGet 包并根据以下两个链接中的信息配置了所有内容):

http://fluentvalidation.codeplex.com/wikipage?title=mvc https://github.com/ninject/ninject.web.mvc.fluentvalidation

4

2 回答 2

4

我想出了如何防止这个问题。尽管这解决了我的问题,但我想从其他人那里得到关于这样做是否有任何后果的意见?

因此,在第二个链接上,您将看到有关如何设置 Ninject 的说明。

在第二步中,您需要应用“ InRequestScope() ”扩展方法。然后,构造函数只会在每个使用验证器的 http 请求中被命中一次。这显然意味着每个 http 请求只创建一个验证器对象实例,这对我来说很有意义。我不知道使用这个解决方案是否有任何后果?

Bind(match.InterfaceType).To(match.ValidatorType).InRequestScope();
于 2011-10-21T02:08:21.717 回答
0

复活这个线程。

我对 SimpleInjector 有同样的问题。我的解决方案是在收集寄存器中包含 LifeTime.Scoped。

private static void WarmUpMediatrAndFluentValidation(this Container container)
    {
        var allAssemblies = GetAssemblies();

        container.RegisterSingleton<IMediator, Mediator>();
        container.Register(typeof(IRequestHandler<,>), allAssemblies);

        RegisterHandlers(container, typeof(INotificationHandler<>), allAssemblies);
        RegisterHandlers(container, typeof(IRequestExceptionAction<,>), allAssemblies);
        RegisterHandlers(container, typeof(IRequestExceptionHandler<,,>), allAssemblies);

        //Pipeline
        container.Collection.Register(typeof(IPipelineBehavior<,>), new[]
        {
            typeof(RequestExceptionProcessorBehavior<,>),
            typeof(RequestExceptionActionProcessorBehavior<,>),
            typeof(RequestPreProcessorBehavior<,>),
            typeof(RequestPostProcessorBehavior<,>),
            typeof(PipelineBehavior<,>)
        });
        
        container.Collection.Register(typeof(IRequestPreProcessor<>), new[] {typeof(EmptyRequestPreProcessor<>)});
        container.Collection.Register(typeof(IRequestPostProcessor<,>), new[] {typeof(EmptyRequestPostProcessor<,>)});

        container.Register(() => new ServiceFactory(container.GetInstance), Lifestyle.Singleton);

        container.Collection.Register(typeof(IValidator<>), allAssemblies, Lifestyle.Scoped);
    }

container.Collection.Register(typeof(IValidator<>), allAssemblies, Lifestyle.Scoped ); <- 工人对我很好,每个请求只调用一次。

于 2021-05-19T15:10:47.943 回答