Advanced Automatic Ninject Bindings

A

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

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:

[code]
            var kernel = new StandardKernel();
            kernel.Bind(x =>
            {
                x.FromThisAssembly()
                    .SelectAllClasses()
                    .InheritedFrom(typeof(IService<>))
                    .BindSingleInterface();
            });
[/code]

Implementing Ninject.extensions.conventions

The above solution works extremely well when you have many services, repositories, or perhaps behaviors that apply the Command Pattern where there is a single interface that many classes can leverage.

To further the above solution, here is some example code the provides the complete picture.

Basic IService.cs example:

[code]
 using System;

 namespace UnitTestProject3
 {
   public interface IService<T>
   {
     T Get(int id);
   }
 }
 [/code]

Basic UserService.cs example:

[code]
 using System;
 using System.Collections.Generic;

 namespace UnitTestProject3
 {
    public class UserService : IService<object>
    {
       private readonly List<object> _users;

       public UserService(List<object> users)
       {
          _users = users;
       }

       public object Get(int id)
       {
          return _users[id];
       }
   }
}
[/code]

And here is a single unit test asserting our binding:

[code]
 using System;
 using Microsoft.VisualStudio.TestTools.UnitTesting;
 using Ninject;
 using Ninject.Extensions.Conventions;

 namespace UnitTestProject3
 {
    [TestClass]
    public class UnitTest1
    {

       [TestMethod]
       public void TestMethod1()
       {
          var kernel = new StandardKernel();
          kernel.Bind(x =>
           {
             x.FromThisAssembly()
            .SelectAllClasses()
            .InheritedFrom(typeof(IService<>))
            .BindSingleInterface();
           });

           var userService = kernel.Get<IService<object>>();
           Assert.IsInstanceOfType(userService, typeof(UserService));
       }
    }
 }
 [/code]

About the author

By Jamie

My Books