Automatic Ninject Bindings Automatic Ninject Bindings

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.



 IKernel kernel = new StandardKernel();
 kernel.Bind(x =>
 {
    x.FromThisAssembly()
    .SelectAllClasses()
    .BindDefaultInterface();
 });

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.

Published on Jan 7, 2014

Tags: ASP.NET MVC and Web API Tutorial | c# | ninject

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.