DEV Community

Robin van der Knaap
Robin van der Knaap

Posted on • Originally published at Medium on

1

Setting up FluentValidation for ASP.NET MVC using Ninject

FluentValidation is a powerful library to validate your model objects fluently. Setting up FluentValidation is easy, import the NugGet package to your project and you’re ready to go. It’s possible to setup FluentValidation using an IoC container, which is very useful when your validators contain some dependencies which you would like to remove using dependency injection. In this article I’ll show you how to use Ninject to setup FluentValidation.

There’s a NuGet package for that!

I’m assuming you already have FluentValidation and Ninject set up for your project. There’s just one little package you need, ninject.web.mvc.fluentvalidation, which you also can grab from NuGet. This package contains a custom validatorfactory which puts Ninject in charge of creating instances of your validators.

First you have to create the ninject factory and configure FluentValidation to use this factory instead of the default one. Add the following lines of code to the Application_Start method in Global.asax or if you’re using webactivator in the start method of the fluentvalidation startup class in App_Start:

NinjectValidatorFactory ninjectValidatorFactory = new NinjectValidatorFactory(Kernel);
FluentValidationModelValidatorProvider
.Configure(x => x.ValidatorFactory = ninjectValidatorFactory);
DataAnnotationsModelValidatorProvider
.AddImplicitRequiredAttributeForValueTypes = false;
view raw gistfile1.cs hosted with ❤ by GitHub

FluentValidation is now using the ninject factory for creating instances of validators. The last step is to bind all validators to their implementation. You can do this with one line of code:

AssemblyScanner.FindValidatorsInAssembly( Assembly.GetExecutingAssembly())
.ForEach(match => kernel.Bind(match.InterfaceType).To(match.ValidatorType));
view raw gistfile1.cs hosted with ❤ by GitHub

This method scans the specified assembly (in this case the current assembly) for validators and binds their interfaces to their implementations. You have to add this method to your Ninject startup script.

By now, all validators can take dependencies which are resolved by Ninject.

Happy programming!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay