Javascript dependency injection & DIP in node: require vs constructor injection

后端 未结 2 1714
南旧
南旧 2021-01-01 03:41

I\'m new to NodeJs development coming from the .NET world i\'m searching the web for best practices regrading DI / DIP in Javascript

In .NET i would declare my depen

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 04:26

    In the past, DI containers as we know them from Java and .NET did not exist. With Node 6 came ES6 Proxies which opened up the possibility of such containers - Awilix for example.

    So let's rewrite your code to modern ES6.

    class Team {
      constructor ({ User }) {
        this.User = user
      }
    
      getTeam (teamId) {
        return this.User.find({ teamId: teamId })
      }
    }
    

    And the test:

    import Team from './Team'
    
    describe('Team', function() {
      it('#getTeam', async function () {
        const users = [{id: 1, id: 2}]
    
        const fakeUser = {
          find: function() {
            return Promise.resolve(users)
          }
        }
    
        const team = new Team({
          User: fakeUser
        })
    
        const team = await team.getTeam()
    
        expect(team).to.eql(users)
      })
    })
    

    Now, using Awilix, let's write our composition root:

    import { createContainer, asClass } from 'awilix'
    import Team from './Team'
    import User from './User'
    
    const container = createContainer()
      .register({
        Team: asClass(Team),
        User: asClass(User)
      })
    
    // Grab an instance of Team
    const team = container.resolve('Team')
    // Alternatively...
    const team = container.cradle.Team
    
    // Use it
    team.getTeam(123) // calls User.find()
    

    That's as simple as it gets; Awilix can handle object lifetimes as well, just like the .NET / Java containers did. This lets you do cool stuff like inject the current user to your services, intantiating your services once per http request, etc.

提交回复
热议问题