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.
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:
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:
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.