简体   繁体   English

如何在ASP.NET Web-API项目中将FluentValidation与LightInject一起使用

[英]How to use FluentValidation with LightInject in asp.net web-api project

I'm trying to inject a service using the IoC container into a Validation class. 我试图将使用IoC容器的服务注入到Validation类中。 See the example below: 请参阅以下示例:

[Validator(typeof(UserPayloadValidator))]
public class UserPayload
{
    public int UserId { get; set; }
}

public class UserPayloadValidator : AbstractValidator<UserPayload>
{
    private IUserService _userService;

    public UserPayloadValidator(IUserService userService)
    {
        _userService = userService;

        RuleFor(x => x.UserId).Must(BeUnique).WithMessage("This user already exists");
    }

    private bool BeUnique(int userId)
    {
        var user = _userService.GetUser(userId);

        return user == null;
    }
}

At this point I was hoping everything would auto-magically work and the userService would be injected into the validation class. 在这一点上,我希望一切都能自动神奇地工作,并将userService注入到验证类中。 Instead, I get an exception complaining about a parameter-less constructor not being found. 相反,我遇到了一个异常,抱怨找不到一个无参数的构造函数。

After some reasearch I've attempted to create a ValidationFactory as in the example linked. 一些经过reasearch我试图创建一个ValidationFactory作为链接的例子。

public class LightInjectValidationFactory : ValidatorFactoryBase
{
    private readonly ServiceContainer _serviceContainer;

    public LightInjectValidationFactory(ServiceContainer serviceContainer)
    {
        _serviceContainer = serviceContainer;
    }

    public override IValidator CreateInstance(Type validatorType)
    {
        return _serviceContainer.TryGetInstance(validatorType) as IValidator;
    }   
}

and in the LightInject configuration 并在LightInject配置中

//Set up fluent validation
FluentValidationModelValidatorProvider.Configure(httpConfiguration, provider =>
{
    provider.ValidatorFactory = new LightInjectValidationFactory(container);
});

This results in an exception: Unable to resolve type: FluentValidation.IValidator`1 这将导致异常:无法解析类型:FluentValidation.IValidator`1

I guess the IoC container doesn't know how to resolve the correct instance for the validator. 我想IoC容器不知道如何为验证程序解析正确的实例。

Any ideas are much appreciated. 任何想法都非常感谢。

Thanks to the comment above I realized I wasn't actually registering the validator in container. 感谢上面的评论,我意识到我实际上并没有在容器中注册验证器。 This can be done like this for all the validators: 对于所有验证器,可以这样做:

FluentValidation.AssemblyScanner.FindValidatorsInAssemblyContaining<UserPayloadValidator>()
            .ForEach(result =>
            {
                container.Register(result.InterfaceType, result.ValidatorType);
            });

Please note that UserPayloadValidator needs to be just one of your validators. 请注意, UserPayloadValidator需要只是您的验证之一 Based on this type, FindValidatorsInAssembly can infer all the other available validators. 基于此类型,FindValidatorsInAssembly可以推断所有其他可用的验证器。

Also, in the validation factory you should use TryGetInstance instead of GetInstance in case the factory tries to instantiate non existant validators (parameter in the controller for which validators do not exist) 另外,在验证工厂中,如果工厂尝试实例化不存在的验证器(控制器中不存在验证器的参数),则应使用TryGetInstance而不是GetInstance。

I have found solution for all validation classes use injected service. 我发现所有验证类的解决方案都使用注入服务。

Replace below code 替换下面的代码

FluentValidation.AssemblyScanner.FindValidatorsInAssemblyContaining<UserPayloadValidator>()
            .ForEach(result =>
            {
                container.Register(result.InterfaceType, result.ValidatorType);
            });

With

FluentValidation.AssemblyScanner findValidatorsInAssembly = FluentValidation.AssemblyScanner.FindValidatorsInAssembly(typeof(UserPayloadValidator).Assembly);
            foreach (FluentValidation.AssemblyScanner.AssemblyScanResult item in findValidatorsInAssembly)
            {
                container.Register(item.InterfaceType, item.ValidatorType);
            }

Using this your all validator classes use injected service. 使用此方法,所有验证器类都使用注入服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在ASP.net Web-API中使用CustomExceptionException处理程序 - How to use customexceptionhandlers in ASP.net web-api PHP / ASP.NET MVC Web-Api有人知道如何使用PHP通过POST调用WEBAPI - PHP/ASP.NET MVC Web-Api Somebody Know How To Use PHP To Call WEBAPI With POST 将类库项目添加到asp.net Web-api项目(REST服务) - adding a Class Library project to a asp.net web-api project (REST service) 从控制台项目类访问asp.net Web-api项目类中的静态属性 - Accessing a static property in a asp.net web-api project class from a console project class asp.net Web-Api JSON字符串反序列化 - asp.net Web-Api JSON string deserialization Asp.net为web-api解雇重定向的核心授权 - Asp.net core authorization for web-api firing redirect 我应该将RouteParameter或UrlParameter用于Asp.NET web-api路由吗? - Should I use RouteParameter or UrlParameter for an Asp.NET web-api route? 如何引用已经在 API 级别声明的 Object? (asp.net web-api) - How to reference Object that it has been already declared at the API level? (asp.net web-api) ASP.net Web-api中的简单类型JSON序列化 - Simple types JSON serialization in ASP.net Web-api 如何通过ID发送消息到signalR特定的PersistentConnection? (使用asp.net mvc4 web-api) - How to send message to signalR specific PersistentConnection by its ID ? (with asp.net mvc4 web-api)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM