How to inject dependencies into a FluentValidation AbstractValidator constructor, with Ninject and MVC4?

StackOverflow https://stackoverflow.com/questions/21462036

Question

I'm using Ninject 3.0.1.10, MVC 5.0.0, FluentValidation 5.0 and finally FluentValidation MVC plugin library.

I'm trying to configure Ninject so that it injects a service into my AbstractValidator classes. I've read a lot of other answers about how to do this, but none have quite made sense to me. They all mention AssemblyScanner, which I can't find. They also mention accessing the IKernal from App_Start, but in my project App_Start does not have access to the IKernal because it's created inside of a NinjectWebCommon.cs file.

So I'm confused as to how to properly make this happen. Anybody have any clarity on this? Thanks.

Was it helpful?

Solution

You can access the IKernel configured by NinjectWebCommon.cs anywhere in your application. Of course, this usually is not recommended since it's a smell of Service Locator anti-pattern.

But there are cases where we can't escape from it, specially when mixing the frameworks and in your composition root, it's ok.

So, wherever you need, just use:

using Ninject;

//My class that will need access to the IKernel
var kernel = (new Bootstrapper()).Kernel;

The Bootstrapper class is initialized in App_Start.NinjectWebCommon before even the Application_OnStart runs. So it is safe to use even in Global.asax to obtain a reference to the IKernel. It remembers the kernel instance that was provided to it via a static variable inside the Bootstrapper class.

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top