What are the benefits of dependency injection containers?

前端 未结 16 2744
南笙
南笙 2020-12-02 04:09

I understand benefits of dependency injection itself. Let\'s take Spring for instance. I also understand benefits of other Spring featureslike AOP, helpers of different kind

16条回答
  •  粉色の甜心
    2020-12-02 04:51

    For myself one of the main reasons to use an IoC (and make use of external configuration) is around the two areas of:

    • Testing
    • Production maintenance

    Testing

    If you split your testing into 3 scenarios (which is fairly normal in large scale development):

    1. Unit testing
    2. Integration testing
    3. Black box testing

    What you will want to do is for the last two test scenarios (Integration & Black box), is not recompile any part of the application.

    If any of your test scenarios require you to change the configuration (ie: use another component to mimic a banking integration, or do a performance load), this can be easily handled (this does come under the benefits of configuring the DI side of an IoC though.

    Additionally if your app is used either at multiple sites (with different server and component configuration) or has a changing configuration on the live environment you can use the later stages of testing to verify that the app will handle those changes.

    Production

    As a developer you don't (and should not) have control of the production environment (in particular when your app is being distributed to multiple customers or seperate sites), this to me is the real benefit of using both an IoC and external configuration, as it is up to the infrastructure/production support to tweak and adjust the live environment without having to go back to developers and through test (higher cost when all they want to do is move a component).

    Summary

    The main benefits that external configuration of an IoC come from giving others (non-developers) the power to configure your application, in my experience this is only useful under a limited set of circumstances:

    • Application is distributed to multiple sites/clients where environments will differ.
    • Limited development control/input over the production environment and setup.
    • Testing scenarios.

    In practice I've found that even when developing something that you do have control over the environment it will be run on, over time it is better to give someone else the capabilities to change the configuration:

    • When developing you don't know when it will change (the app is so useful your company sells it to someone else).
    • I don't want to be stuck with changing the code every time a slight change is requested that could have been handled by setting up and using a good configuration model.

    Note: Application refers to the complete solution (not just the executable), so all files required for the application to run.

提交回复
热议问题