简体   繁体   中英

Inversion of Control and Dependency Injection - I need your advice

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM