尝试使用 MediatR 在 .Net Core 3.1 微服务中注入 Fluent Validation而不使用Structure Map。
在 Nuget 包下面添加:
<PackageReference Include="FluentValidation.AspNetCore" Version="8.6.2" />
<PackageReference Include="MediatR" Version="4.0.1" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="4.0.0" />
Run Code Online (Sandbox Code Playgroud)
启动.cs:
services.AddMvc(options =>
{
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
options.EnableEndpointRouting = false;
}).AddControllersAsServices()
.AddNewtonsoftJson()
.AddViewLocalization(
LanguageViewLocationExpanderFormat.Suffix,
opts => { opts.ResourcesPath = "Resources"; })
.AddDataAnnotationsLocalization()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddFluentValidation(fv=> fv.RegisterValidatorsFromAssemblyContaining(typeof(Startup)));
Run Code Online (Sandbox Code Playgroud)
注册的 IPipelineBehavior 和验证器:
services.AddMediatR();
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehaviour<,>));
Run Code Online (Sandbox Code Playgroud)
ValidatorBehaviour.cs:
public class ValidatorBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly IValidator<TRequest>[] _validators;
public ValidatorBehaviour(IValidator<TRequest>[] validators) => _validators = validators;
public async Task<TResponse> Handle(TRequest …Run Code Online (Sandbox Code Playgroud)