Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to easily tell if Ninject can resolve a class

I'm introducing Ninject into a large mess of a existing project. I want to write a diagnostic test to make sure that all of the classes Ninject will end up creating can actually BE resolved by Ninject...without actually creating any of them.

The reason I want to avoid the actual construction is that many of these classes have a tendency to start up database operations in their constructors (sigh yes I know). Otherwise I would just run them all through Get<T> with a try/catch

like image 465
ryber Avatar asked Nov 12 '10 22:11

ryber


2 Answers

There's a CanResolve extension on IResolutionRoot (i.e., you can use it against Kernel if you have the right usings in place). There's a CreateRequest that you use to create the request. Have a look in the sources and tests if you need an example or any deeper information.

like image 154
Ruben Bartelink Avatar answered Sep 23 '22 02:09

Ruben Bartelink


I know this is an old post but it was the first one I found when searching for how to find if a class can be resolved by Ninject without actually calling get() and risking an exception.

Ninject version 3.0.2 have a method CanResolve which returns a boolean:

kernel.CanResolve<T>()

I got 3.0.2 from nuget but its currently market unstable (Ninject.3.0.2-unstable-9037) so I'm not sure if I use this in production just yet.

like image 29
Filip Avatar answered Sep 21 '22 02:09

Filip