Where and how to specify initializer for an ember engine?

528 Views Asked by At

In my application, I have used initializers to inject services to routes, controllers and components. I am trying to use ember engine now. I have shared my application services to my engine, but I need to inject the shared application services to the engine's routes, controllers and components using an initializer.

In my application, I can generate an initializer and inject the services. How to do that in my engine?

3

There are 3 best solutions below

0
On

This command should create the initializer in the proper folder under the in-repo-engine:

ember g initializer <init-name> -ir <engine-name>

Ideally, injecting a service into a controller/route/component is best done as stated in the other answer.

Refer: https://guides.emberjs.com/release/applications/dependency-injection/#toc_ad-hoc-injections

0
On

It may be substantially easier to require it where needed instead of injecting it everywhere.

An example from the Ember Docs:

import Component from '@ember/component';
import { inject as service } from '@ember/service';

export default Component.extend({
  shoppingCart: service()
});

This would make the shopping cart service available here. You can do the same thing in routes and controllers and that service is a singleton so it will only be instantiated once and shares state between every location it is accessed.

This avoids needing to mess with creating an engine specific initializer entirely.

0
On

I actually found out that initializers for an engine can be configured similarly to the initializers for an application. It can be specified in the lib/<engine>/addon/initializers directory.

If you want to inject services to routes, components and controllers, you must first share the services from the app to the engine as explained in the engine docs.