1

In a typical non-DI application, when you enter a section of code the necessary objects are constructed and when you leave it they are deconstructed.

However, when doing dependency injection with a composition root, you typically instantiate the whole application graph at startup. Sometimes (if your application is lightweight) this isn't a problem. However, if you have any elements in your application with large, heavy constructors then startup time immediately suffers.

Is there a standard way around this while still using dependency injection?

1
  • 3
    Flippant comment here, but the answer to "Is there a standard way..." is don't instantiate the whole application graph at start up. The are various way that you can do this, such as not having a single composition root (though this is frowned upon by some) and using lazy initialisation techniques such as injecting factories. It largely depends on whether your composition root using pure DI or a container and how that container is implemented.
    – David Arno
    May 31, 2019 at 8:09

1 Answer 1

4

Say I want a timestamp that represents now. I can't create it at startup because at startup nothing knows when now is. I also don't want to hardcode the timestamp because I don't want to be tied to a particular timestamp implementation. All I want is a string that represents now. So long as that's formatted correctly I don't want to know what class implemented it.

This can be achieved with an injectable factory. The abstract factory pattern structure works for this even without a hierarchy. The code that knows when doesn't know what. The code that knows what doesn't know when. This can achieve the same lazy initialisation as a singleton pattern without globals because when may never happen.

Pass me an object with a method that will build what I need when I ask for it. Just be careful to keep the thing you pass me focused on my needs. Pass me something that builds or finds everything's needs and you've reinvented the service locator pattern.

The above might seem trivial at first but you should realize that the same pattern that gave you one time stamp could also give you an entire object graph constructed on demand that is now just waiting for you to call start.

If you're a dependency injection purist you can also keep the call to construct and the call to start separate. "Now" just becomes your composition root for this on demand object graph.

1
  • That's a good explanation of how to do this type of thing, and you make me wonder about a name to call this technique: Heisemberg's Coding.
    – T. Sar
    Jun 17, 2019 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.