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



Discussion


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:

 using System;

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

Basic UserService.cs example:

 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];
       }
   }
}

And here is a single unit test asserting our binding:

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

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

Related Posts

blog comments powered by Disqus