Thursday, 14 January 2021

Create class instance and inject it dynamically

My project is using Nuxt, and I would like to implement dynamic injection of my services. It means I just add a class to my specific folder, and the class will be automatically injected into the context.

For instance, these are my classes placed in nuxtApp/service:

// /service/foo.service.js
export class FooService {
  constructor (context) {
    this.context = context
  }
  
  functionFoo (param) {
    console.log(`FooService.functionFoo: ${param}`)
  }
}

// /service/bar.service.js
export class BarService {
  constructor (context) {
    this.context = context
  }
  
  functionBar (param) {
    console.log(`BarService.functionBar: ${param}`)
  }
}

And this is how my plugin currently looks like, but I would like to automate it:

// /plugins/service-loader.js
import { FooService } from '../service/foo.service'
import { BarService } from '../service/bar.service'

export default ({ app }, inject) => {
  const fooService = new FooService(app)
  inject('fooService', fooService)

  const barService = new BarService(app)
  inject('barService', barService)
}

Is it possible to create automatically loading of services placed in the /service folder, and then inject their instance into the context?



from Create class instance and inject it dynamically

No comments:

Post a Comment