开发者

Injecting a DbContext into a FluentValidation validator

开发者 https://www.devze.com 2023-03-29 07:43 出处:网络
I am using the FluentValidation library to enforce a unique constraint on one of my models: public class Foo {

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

public class Foo {
    // No two Foos ca开发者_开发技巧n 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)?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号