Advanced Automatic Ninject Bindings

Published on Jan 13, 2014 by Jamie Munro

Problem


You have a common interface that is used by multiple concrete classes and you donít want to specify each Ninject binding manually.

Solution


The solution to this problem is very similar to my previous post on Automatic Ninject Bindings because it also leverages the NuGet package Ninject.extensions.conventions.

In this example, letís assume you have a single interface called IService<T>.† This interface contains a generic reference to a class or object (e.g. a database model).† Then you have multiple classes that implement the interface.† E.g. UserService : IService<User>.

With the following line of code, all of your classes that implement the IService interface will automatically bind to the corresponding class:


 ††††††††††† var kernel = new StandardKernel();

 ††††††††††† kernel.Bind(x =>

 ††††††††††† {

 †††† †††††††††††x.FromThisAssembly()

 ††††††††††††††††††† .SelectAllClasses()

 ††††††††††††††††††† .InheritedFrom(typeof(IService<>))

 ††††††††††† ††††††††.BindSingleInterface();

 ††††††††††† });

 

Read more >

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

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

 });


Read more >

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