When do I use abstract classes versus interfaces with regards to dependency Injection?

前端 未结 6 925
名媛妹妹
名媛妹妹 2021-02-08 18:23

I have been reading some articles about the SOLID principles and dependency Inversion. From my point of view, I must use an interface to talk to any class. My classes are chatti

6条回答
  •  说谎
    说谎 (楼主)
    2021-02-08 19:06

    based on what I see you aren't really using an interface at all. Sure you implement the methods, but the consuming class shouldn't really know or even care about the implementation. Therefore, you shouldn't really see any reference or casting to Sms. You should be using a IoC framework such as Unity, Ninject, structuremap. If you actually need a public property returning an IMessage, it should return IMessage and not Sms, whether you should be doing that is a different conversation.

    That said, the first Usage doesn't have anything in the IMessage so it is worthless. Also, I often use an abstract / base class to handle common functionality between multiple implementations of an interface. In you scenario, there is no need for the abstract class. The only time I create abstract methods without any code is if the abstract class actually fires that method in some capacity but expects the derived class to implement the functionality.

    Anyway, to answer you question Usage #2 seems closer to the correct solution, but just remove the references to Sms and let an IoC container handle that.

提交回复
热议问题