【问题标题】:How to use Fluent Validation in Repository Pattern in .Net?如何在 .Net 的存储库模式中使用流畅的验证?
【发布时间】:2020-07-08 16:12:46
【问题描述】:

我在 .Net core Repositoy Pattern 中进行了 CRUD 操作并尝试实现 FluidValidation,但我收到运行时错误“TypeLoadException: Method 'GetValidationVisitor' in type 'FluentValidation.AspNetCore.FluentValidationObjectModelValidator' from assembly 'FluentValidation.AspNetCore, Version =8.0.0.0, Culture=neutral, PublicKeyToken=7de548da2fbae0f0' 没有实现”。

我的代码是

public class ActivitiesService : AbstractValidator<Activity>,IActivitiesService
    {
        private readonly DataContext _dataContext;

        public ActivitiesService(DataContext dataContext)
        {
            _dataContext = dataContext;

            RuleFor(x => x.Title).NotNull();
            RuleFor(x => x.Description).NotEmpty();
            RuleFor(x => x.Category).NotEmpty();
            RuleFor(x => x.Date).NotEmpty();
            RuleFor(x => x.City).NotEmpty();
            RuleFor(x => x.Venue).NotEmpty();
        }

       
        public async Task<AccountResult> CreateActivity(Activity activity)
        {
            var resultMessage = new AccountResult();
            _dataContext.Activities.Add(activity);
            await _dataContext.SaveChangesAsync();

            return resultMessage;

        }

       
    }

ActivityService 继承自 Interface

我的 startup.cs 代码是:

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("PreactivitiesDBConnection")));

            services.AddCors(opt => {
                opt.AddPolicy("CorsPolicy", policy => {
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3000");
                });
            });
            
            services.AddControllers().AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);

            services.AddScoped<IActivitiesService, ActivitiesService>();
            services.AddMediatR(typeof(List.Handler).Assembly);
            services.AddMvc(option => option.EnableEndpointRouting = false).AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<ActivitiesService>());

        }

【问题讨论】:

    标签: c# asp.net .net-core fluentvalidation


    【解决方案1】:

    如此链接所示,问题已通过使用最新版本升级 FluentValidation.AspNetCore 解决。

    https://www.nuget.org/packages/FluentValidation.AspNetCore/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      相关资源
      最近更新 更多