Overview

Remo Gloor edited this page Aug 8, 2013 · 9 revisions

Referencing the Conventions Extension

First of all you have to add an assembly reference to Ninject.Extensions.Conventions (it's available on NuGet) and a namespace reference for Ninject.Extensions.Conventions to bring the extension methods into scope.

Elements of a convention

Having referenced the Ninject Conventions Extension, you can begin to specify convention based registrations such as this:

kernel.Bind( x => x
    .FromThisAssembly() // 1
    // .IncludingNonePublicTypes()
    .SelectAllClasses().InNamespaceOf<MyService>() // 2
    .BindAllInterfaces() // 3
    .Configure(b => b.InSingletonScope())); // 4

Each registration consists of four elements:-

  1. Projecting Assemblies from within which the components to be bound are to be selected
  2. Projecting Components from within those assemblies which are to supply services (the To<X>() bit in explicit bindings terms)
  3. Projecting Services to Bind for each projected component (the Bind<X>() bit in explicit bindings terms)
  4. Configuring Bindings for each projected service(the .In..., .With... etc. bits in explicit bindings terms)

Combining multiple assembly/service selections into a single convention-registration

The first two portions can be repeated in case the criteria for the selection of the components differs across assembly groupings.

kernel.Bind( x => x
    .FromThisAssembly() // 1a
    .SelectAllClasses().InNamespaceOf<MyService>() // 2a
    .Join.FromAssembliesInPath(".") // 1b
    .SelectAllClasses().InheritedFrom<IService>() // 2b
    .BindAllInterfaces() // 3
    .Configure(b => b.InSingletonScope())); // 4

(In pre 3.0 versions of the extension, this combined criteria was expressed by having multiple .From() clauses.)


Continue Reading: Projecting Assemblies
Back: What is configuration by convention?