Dependency Injection vs Service Location

前端 未结 11 1385
梦如初夏
梦如初夏 2020-11-28 03:59

I am currently weighing up the advantages and disadvantages between DI and SL. However, I have found myself in the following catch 22 which implies that I should just use SL

11条回答
  •  心在旅途
    2020-11-28 05:02

    Sometimes logging can be implemented using AOP, so that it doesn't mix with business logic.

    Otherwise, options are :

    • use an optional dependency (such as setter property), and for unit test you don't inject any logger. IOC container will takes care of setting it automatically for you if you run in production.
    • When you have a dependency that almost every object of your app is using ("logger" object being the most commmon example), it's one of the few cases where the singleton anti-pattern becomes a good practice. Some people call these "good singletons" an Ambient Context: http://aabs.wordpress.com/2007/12/31/the-ambient-context-design-pattern-in-net/

    Of course this context has to be configurable, so that you can use stub/mock for unit testing. Another suggested use of AmbientContext, is to put the current Date/Time provider there , so that you can stub it during unit test, and accelerates time if you want.

提交回复
热议问题