Inject different classes that implement the same interface using Ninject

前端 未结 2 775
Happy的楠姐
Happy的楠姐 2021-02-03 11:27

I am implementing the builder design pattern to construct different kinds of graph objects to be displayed on a WPF UI. I am using Ninject as my IOC container. However, I am try

2条回答
  •  逝去的感伤
    2021-02-03 11:47

    If you're just planning to use service location, as in your examples, then named bindings work fine, as per Garys answer.

    A better approach, however, is to use constructor injection, and use attributes. For exampl, from the ninject wiki:

    Bind().To().Named("Strong");
    Bind().To().Named("Weak"); 
    

    ...

    class WeakAttack {
        readonly IWeapon _weapon;
        public([Named("Weak")] IWeapon weakWeapon)
            _weapon = weakWeapon;
        }
        public void Attack(string victim){
            Console.WriteLine(_weapon.Hit(victim));
        }
    }
    

    Based on your comment to Gary, you're (strangely enough) stumbling into territory similar to what I asked a question about a few hours ago. See Remo's answer here: Using WithConstructorArgument and creating bound type

    You would use When condition to define when to create the correct instance.

提交回复
热议问题