Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: Fluent Validation + Service Layer

$
0
0
Yes - the problem was that you were injecting a transient service into a singleton validator. This ends up forcing the service to be a singleton as well. Using a lazily-evaluated Func<T> is indeed the correct solution.

Jeremy Skinner
Sent from my iPhone

On 4 Jan 2012, at 22:42, shapper <notifications@codeplex.com> wrote:

From: shapper

Hello,

On a MVC 3 site I have the following validator:

  public class RoleNewModelValidator : AbstractValidator<RoleNewModel> {   

    public RoleNewModelValidator(IRequestDispatcher dispatcher) {
      
      RuleFor(x => x.Name)
        .Must(name => dispatcher.Get<FindRoleByNameResponse>(new FindRoleByNameRequest { Name = name }).Role == null).WithMessage("Role already exists");

    }
  }

My IoC configuration is as follows:

AssemblyScanner.FindValidatorsInAssembly(Assembly.GetExecutingAssembly()).ForEach(x => { For(x.InterfaceType).Singleton().Use(x.ValidatorType); });
For<IRequestDispatcher>().Transient().Use<RequestDispatcher>();

It seems logic to me to have the Validator as singleton and the Dispatcher as Transient.

The Agatha Dispatcher is used to access the Service layer. Every time is used it needs to be cleared.

To avoid problems I set it as transient. It works fine everywhere but not in the validator.

It works fine on the first form submission with error. On the second submission with error I get the message to clear the dispatcher.

Maybe because the dispatcher is being used in a Validator defined as Singleton? So I changed it to:

  public class RoleNewModelValidator : AbstractValidator<RoleNewModel> {   

    public RoleNewModelValidator(Fun<IRequestDispatcher> dispatcher) {
      
      RuleFor(x => x.Name)
        .Must(name => dispatcher().Get<FindRoleByNameResponse>(new FindRoleByNameRequest { Name = name }).Role == null).WithMessage("Role already exists");

    }
  }

Now I am able to submit the form many times without errors. Is this a good option to use Services inside a Fluent Validator?

Thank You,

Miguel


Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>