DI Framework

So there's a fancy new Hamburger class that is easy to test, but it'scurrently awkward to work with. Instantiating a Hamburger requires:

  1. const hamburger = new Hamburger(new Bun(), new Patty('beef'), new Toppings([]));

That's a lot of work to create a Hamburger, and now all the different piecesof code that make Hamburgers have to understand how Bun, Patty andToppings get instantiated.

One approach to dealing with this new problem might be to make a factoryfunction like so:

  1. function makeHamburger() {
  2. const bun = new Bun();
  3. const patty = new Patty('beef');
  4. const toppings = new Toppings(['lettuce', 'tomato', 'pickles']);
  5. return new Hamburger(bun, patty, toppings);
  6. }

This is an improvement, but when more complex Hamburgers need to be createdthis factory will become confusing. The factory is also responsible forknowing how to create four different components. This is a lot for onefunction.

This is where a dependency injection framework can help. DI Frameworkshave the concept of an Injector object. An Injector is a lot likethe factory function above, but more general, and powerful. Instead of onegiant factory function, an Injector has a factory, or recipe (pun intended)for a collection of objects. With an Injector, creating a Hamburger could beas easy as:

  1. const injector = new Injector([Hamburger, Bun, Patty, Toppings]);
  2. const burger = injector.get(Hamburger);

原文: https://angular-2-training-book.rangle.io/handout/di/di_framework.html