• 5 Subscribers
  • 114 Views
1

i wrote a little example to learn IoC and DI on my own. I have one simple question:

How would you instantiate the unskilled worker in my example /

How can I swich between the following 2 inject candidates?:

kernal.Bind<IRepair>().To<Employee>();

kernal.Bind<IRepair>().To<UnskilledWorker>() 

I'm a little bit confused at the moment...

    class Program
    {
        static void Main(string[] args)
        {
            IWorkShop instance = GetWorkShop();
            instance.StartToRepair();

            Console.ReadLine();
        }

        private static IWorkShop GetWorkShop()
        {
            Ninject.IKernel kernal = new StandardKernel();
            kernal.Bind<IWorkShop>().To<WorkShop>();
            kernal.Bind<IRepair>().To<Employee>();


            var instance = kernal.Get<IWorkShop>();
            return instance;
        }
    }

    public class WorkShop : IWorkShop
    {
        private IRepair _repair;

        public WorkShop(IRepair repair)
        {
            _repair = repair;
        }

        public void StartToRepair()
        {
            _repair.RepairItNow();
        }
    }


    interface IWorkShop
    {
        void StartToRepair();
    }


    public class Employee : IRepair
    {
        public void RepairItNow()
        {
            Console.WriteLine("Employee starts working.");
        }
    }

    public class UnskilledWorker : IRepair
    {
        public void RepairItNow()
        {
            Console.WriteLine("Unskilled worker starts working.");

        }
    }


    public interface IRepair
    {
        void RepairItNow();
    }
}

1 answers in total

2
Jason Boyd Posted at 2017-01-03 17:50:48Z

If you know at compile time then you can use Ninject's contextual bindings: https://github.com/ninject/ninject/wiki/Contextual-Binding.

IKernel kernal = new StandardKernel();
kernal.Bind<IWorkShop>().To<WorkShop>();
kernal.Bind<IRepair>().To<Employee>();
kernal.Bind<IRepair>().To<UnskilledWorker>().WhenInjectedInto(typeof(IWorkShop));

var instance = kernal.Get<IWorkShop>();
return instance;

If you need to decide at runtime which dependency to instantiate you are going to have to use a factory pattern.

Answer this questsion