Ninject Multicasting

天大地大妈咪最大 提交于 2019-12-05 05:24:04

If you use constructor injection and have a List<IBreakfast> parameter, then Ninject will construct a list using all your bindings. You can then call Eat on these instances.

You can use this pattern to get Ninject to create a list of your plugins for instance.

    [Test]
    public void Test()
    {
        IKernel kernel = new StandardKernel();

        kernel.Bind<IBreakfast>().To<Eggs>();
        kernel.Bind<IBreakfast>().To<Spam>();
        kernel.Bind<IBreakfast>().To<MoreSpam>();

        var bling = kernel.Get<Bling>();
    }

    private class Bling
    {
        public Bling(List<IBreakfast> things)
        {
            things.ForEach(t => t.Eat());
        }
    }

    private interface IBreakfast
    {
        void Eat();
    }

    private class Ingrediant : IBreakfast
    {
        public void Eat(){Console.WriteLine(GetType().Name);}
    }

    private class Eggs : Ingrediant{}
    private class Spam : Ingrediant{}
    private class MoreSpam : Ingrediant { }

Output:

Eggs
Spam
MoreSpam

You can't bind many concrete classes to once single interface, that's against DI rules.

What basically you want to do is, initialize couple of concrete instances and call their method.

You may want to check this out:

Bind<IBreakfast>.To<Spam>().Named("Spam");
Bind<IBreakfast>.To<Eggs>().Named("Eggs");
Bind<IBreakfast>.To<MoreSpam>().Named("MoreSpam");

var breakfastList = new List() { "Spam", "Eggs", "MoreSpam" };
breakfastList.ForEach(item => kernel.Get<IBreakfast>(item).Eat());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!