A day with .Net

My day to day experince in .net

Injecting different implementation of same interface via Ninject – Contextual Injection

Posted by vivekcek on May 8, 2016

Hi Guys,

I was just working on combining a Factory Method Pattern with Strategy Pattern. During this i came across contextual injection.
Please refer my old post.
Strategy Pattern
Factory Method Design Pattern

I have a common Factory interface, But i want to use separate implementation of this same interface in my two controllers.
I am always using Ninject for all of my MVC app’s. Then I found Ninject have feature for Contextual injection.

Hope You know how to use Ninject, else refer my blog.
Using Ninject

So come to the point.

This is my interface.

    public interface IMyInterface
    {
        void add();
    }

This is my First Implementation.

 public class MyImplementation1 : IMyInterface
    {
        public void add()
        {
            throw new NotImplementedException();
        }
    }

This is my second implementation.

 public class MyImplementation2 : IMyInterface
    {
        public void add()
        {
            throw new NotImplementedException();
        }
    }

The below code can be used for contextual mapping in Ninject

            kernel.Bind<IMyInterface>().To<MyImplementation1>().Named("Implementation1");
            kernel.Bind<IMyInterface>().To<MyImplementation2>().Named("Implementation2");

Now in my First Controller, i can use first implementation.

        IMyInterface _myImpe = null;
        public HomeController([Named("Implementation1")] IMyInterface myImpe)
        {
            _myImpe = myImpe;
        }

In the Second controller.

        IMyInterface _myImpe = null;
        public AccountController([Named("Implementation2")] IMyInterface myImpe)
        {
            _myImpe = myImpe;
        }

For property injection use this snippet.

        [Inject, Named("Implementation2")]
        public IMyInterface Foo { get; set; }

Leave a comment