I'm confused about interface abstractions when using IoC

前端 未结 2 587
栀梦
栀梦 2020-12-06 05:42

I\'ve recently been trying to learn IoC, and have a couple questions based on the following code:

public class WarriorModule : NinjectModule 
{
    public          


        
2条回答
  •  时光取名叫无心
    2020-12-06 06:13

    A good IoC container should not change the way interfaces are used:

    1. An interface should be designed for the component that is using it as dependency and not the class that is implementing it. (interface segregation principle)
    2. A class can implement several interfaces. But this should only be done if those interfaces are for the same kind of service so that the class does exactly one thing. If the interfaces are for two different things they should be implemented by two different classes. (single responsibility principle)
    3. Several classes can implement the same interface if you need multiple strategies for this type of service.

    Ninject allows using interfaces this way using two different concepts:

    1. Conditional bindings: If several classes implement the same interface you have to specify which implementation is used in which case. This is done using conditions:

      Bind().To().When(ctx => TodayIsSunday());

      Bind().To().When(ctx => !TodayIsSunday());

    2. Multiple Interfaces: See my blogpost http://www.planetgeek.ch/2010/12/08/ninject-extension-contextpreservation-explained/

提交回复
热议问题