JavaScript Dependency Injection

后端 未结 12 1566
天涯浪人
天涯浪人 2020-12-22 16:51

I am new at JavaScript. I wonder how dependency injection is being implemented in JavaScript? I searched the internet but couldn\'t find anything.

12条回答
  •  时光说笑
    2020-12-22 17:43

    bubble-di is a lightweight DI container for Javascript and Typescript.

    It enables you to register factory methods (callbacks) or instances. Below is a simple example (more examples).

    npm install --save bubble-di

    var {DiContainer} = require("bubble-di");
    // import { DiContainer } from "bubble-di";
    
    DiContainer.setContainer(new DiContainer());
    
    class Bar { sayBar(){ console.log("bar"); } }
    class Baz { sayBaz(){ console.log("baz"); } }
    class Foo { 
        constructor (bar, baz)
        {
            bar.sayBar();
            baz.sayBaz();
            // ...
        }
    };
    
    DiContainer.getContainer().registerInstance("bar", new Bar());
    DiContainer.getContainer().registerInstance("baz", new Baz());
    DiContainer.getContainer().register("foo", {
        dependencies: ["bar", "baz"],
        factoryMethod: (bar, baz) => new Foo(bar, baz) },
    );
    const foo = DiContainer.getContainer().resolve("foo"); // will print "bar" and "baz".
    

提交回复
热议问题