Automatic Ninject Bindings

Published on Jan 7, 2014 by Jamie Munro

Problem


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.

Solution


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();
 });



Discussion


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.

Tags: ASP.NET | c# | mvc | ninject

Related Posts

blog comments powered by Disqus