Injecting a DbContext into a FluentValidation validator
O

1

16

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)?

Olenolin answered 17/8, 2011 at 19:28 Comment(2)
Maybe the validator is not http scoped (but singleton) and it is not recreated/injected with a new context? So maybe it tries to use a disposed context from a previous request? Just guessing, I don't know StructureMap concretely.Cartload
Your comment was correct, the validation classes were Singleton scoped. Want to submit that as an answer so I can give it credit?Olenolin
C
7

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.

Cartload answered 19/8, 2011 at 6:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.