Automatic Ninject Bindings

A

You have a large project with many interfaces and many different concrete implementations.  Because of this, managing every single Ninject binding is becoming challenging and time consuming.

By leveraging an additional Ninject NuGet package called Ninject.extensions.conventions, you can write a single line (wrapped over several for readability 😉 that will manage all of your Ninject bindings.

[code]
IKernel kernel = new StandardKernel();

kernel.Bind(x =>
{
x.FromThisAssembly()
.SelectAllClasses()
.BindDefaultInterface();
});
[/code]

Automatic Ninject Bindings

The above line of code will automatically scan your current assembly and bind interfaces to any classes that match in naming convention.

The name convention that is used is to drop the I from the interface and look for a concrete class that matches the interface name without the I.  E.g. IUser interface will automatically bind to a concrete class of User.

If the name fails to match exactly, the automatic binding will fail – great way to ensure typos are avoiding when an interface and class are created.

About the author

By Jamie

My Books