将 DbContext 注入 FluentValidation 验证器

发布于 2024-11-30 06:11:47 字数 968 浏览 2 评论 0原文

我正在使用 FluentValidation 库对我的模型之一强制执行唯一约束:

public class Foo {
    // No two Foos can have the same value for Bar
    public int Bar { get; set; }
}

public class FooValidator : AbstractValidator<Foo> {

    public FooValidator(ApplicationDbContext context) {
        this.context = context;

        RuleFor(m => m.Bar)
            .Must(BeUnique).WithMessage("Bar must be unique!");
    }

    private readonly ApplicationDbContext context;

    public bool BeUnique(int bar) {
        return !context.Foos.Any(foo => foo.Bar == bar);
    }
}

使用 StructureMap 注入 ApplicationDbContext 值。为了确保在每个请求结束时释放上下文,我尝试在应用程序的 EndRequest 处理程序中调用 ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects()

不幸的是,似乎在我的验证器类能够完成其工作之前就调用了 Application_EndRequest 方法,并且在执行 FooValidator.BeUnique 时上下文已被释放。

是否有更好的方法来使用 FluentValidation 库执行依赖于数据库的验证,或者是将这个逻辑移到其他地方(控制器操作、数据库本身或其他地方)的唯一解决方案?

I am using the FluentValidation library to enforce a unique constraint on one of my models:

public class Foo {
    // No two Foos can have the same value for Bar
    public int Bar { get; set; }
}

public class FooValidator : AbstractValidator<Foo> {

    public FooValidator(ApplicationDbContext context) {
        this.context = context;

        RuleFor(m => m.Bar)
            .Must(BeUnique).WithMessage("Bar must be unique!");
    }

    private readonly ApplicationDbContext context;

    public bool BeUnique(int bar) {
        return !context.Foos.Any(foo => foo.Bar == bar);
    }
}

The ApplicationDbContext value is injected using StructureMap. To make sure that the context is disposed of at the end of every request, I attempted to call ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects() in the EndRequest handler for my application.

Unfortunately, it appears as though the Application_EndRequest method is called before my validator class is able to do its job and the context is disposed by the time FooValidator.BeUnique is executed.

Is there a better way to perform database-dependent validations with the FluentValidation library, or is the only solution to move this logic elsewhere (either to the controller action, the DB itself, or maybe elsewhere)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最美不过初阳 2024-12-07 06:11:47

也许验证器不是 http 范围的(而是单例的)并且它没有用新的上下文重新创建/注入?在这种情况下,它尝试使用先前请求中已处理的上下文。

Maybe the validator is not http scoped (but singleton) and it is not recreated/injected with a new context? In this case it tries to use a disposed context from a previous request.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文