When to use Dependency Injection

前端 未结 8 963
野性不改
野性不改 2020-12-01 00:19

I\'ve had a certain feeling these last couple of days that dependency-injection should really be called \"I can\'t make up my mind\"-pattern. I know this might sound silly,

8条回答
  •  春和景丽
    2020-12-01 00:35

    While I semi-agree with you with the DB example, one of the large things that I found helpful to use DI is to help me test the layer I build on top of the database.

    Here's an example...

    You have your database.

    You have your code that accesses the database and returns objects

    You have business domain objects that take the previous item's objects and do some logic with them.

    If you merge the data access with your business domain logic, your domain objects can become difficult to test. DI allows you to inject your own data access objects into your domain so that you don't depend on the database for testing or possibly demonstrations (ran a demo where some data was pulled in from xml instead of a database).

    Abstracting 3rd party components and frameworks like this would also help you.

    Aside from the testing example, there's a few places where DI can be used through a Design by Contract approach. You may find it appropriate to create a processing engine of sorts that calls methods of the objects you're injecting into it. While it may not truly "process it" it runs the methods that have different implementation in each object you provide.

    I saw an example of this where the every business domain object had a "Save" function that the was called after it was injected into the processor. The processor modified the component with configuration information and Save handled the object's primary state. In essence, DI supplemented the polymorphic method implementation of the objects that conformed to the Interface.

提交回复
热议问题