Skip to content

Explicit Service Injection - #502

Open
NullVoxPopuli wants to merge 27 commits into
emberjs:mainfrom
NullVoxPopuli:explicit-dependency-injection
Open

NullVoxPopuli wants to merge 27 commits into
emberjs:mainfrom
NullVoxPopuli:explicit-dependency-injection

Conversation

@NullVoxPopuli

@NullVoxPopuli NullVoxPopuli commented Jun 15, 2019 •

Copy link
Copy Markdown
Contributor

To view rendered:

  • files changed
  • click dots
  • view file

Link at the time of updating the PR description:
https://github.com/NullVoxPopuli/rfcs/blob/explicit-dependency-injection/text/0502-explicit-dependency-injection.md

@webark

webark commented Jun 15, 2019

Copy link
Copy Markdown

@NullVoxPopuli Where does the class name come from? Is it just the path camel cased with the type tacked on? Would it be something you import? Is it the class name you define in the individual file that would get pulled out?

@flashios09

flashios09 commented Jun 15, 2019 •

Copy link
Copy Markdown

hi @NullVoxPopuli ,
i like the idea 👏
this will add some imports but it will make the code more clear/readable
i wish if we can do the same with a model
so instead of this:

this.store.findAll('post', '...')

we have:

@service(StoreService) store;
// i prefer the pluralized form, `posts` not `post` for model name
@model(PostsModel) posts;
// ...

doSomething() {
    this.store.findAll(this.posts, '...');
    // or
    this.posts.somePostsModelMethod('...');
   // maybe
   this.posts.findAll('...');
   // a class cased form for model name `Posts` or `PostsModel`
   this.PostsModel.findAll('...');
}

@buschtoens

Copy link
Copy Markdown
Contributor

A few tangents regarding TypeScript.

Currently I (we?) do this for TypeScript:

import Service, { inject as service } from '@ember/service';
import BarService from './bar';

class FooService extends Service {
  @service bar!: BarService;
}

Alternatively you can get around the extra import of BarService, if you provide the service name explicitly and use the old Ember Object Model:

import Service, { inject as service } from '@ember/service';

class FooService extends Service.extends({
  bar: service('bar')
}) {
}

This works because of the clever registry pattern. The reason you have to use the Ember Object Model is that decorators still can't yet change the type signature: microsoft/TypeScript#4881

Once they could, the following should type-check and infer the service class automatically:

import Service, { inject as service } from '@ember/service';

class FooService extends Service {
  @service bar;
}

For the time being, if you don't want to or can't use the Ember Object Model, but dislike explicitly importing the injtectee class, you could use the trick that we discussed in machty/ember-concurrency-decorators#50: Use a Babel transform to convert class property assignments to decorated properties.

import Service, { inject as service } from '@ember/service';

class FooService extends Service {
  bar = service('bar');
}

// gets transformed into

class FooService extends Service {
  @service('bar') bar;
}

I have a transform for it ready, but I need to battle-test and optimize it further:
babel-plugin-transform-class-property-assignment-to-decorator

@gossi

gossi commented Jun 15, 2019

Copy link
Copy Markdown

@buschtoens

Alternatively you can get around the extra import of BarService

if I understand this RFC correctly, it is about explicitely importing the respective class and exchange the string lookup for the class definition.

Second is: As much as we love typescript, this RFC must work for JS and as such the registry pattern from e-c-ts isn't available in pure js land. So with this RFC TS code will look like this:

import Service form '@ember/serivce';
import NotificationsService from 'my-project/services/notifications';

class Foo extends Service {
  @service(NotificationsService) notifications: NotificationsService;
}

at least until decorators can mutate the type definition for properties (then we can get rid of the doubled written class name).

@buschtoens

buschtoens commented Jun 15, 2019 •

Copy link
Copy Markdown
Contributor

@gossi This is exactly why I raised these points. While Ember is committed to not pushing TypeScript onto anybody and offering first-class support for JS, we are equally committed to offering first-class support for TypeScript as well.

I find it important that, as long as decorators cannot change types in TS or using a Babel transform is not a community-accepted and agreed upon opinion, we do not deprecate string lookups, as this could worsen ergonomics for some TypeScript users.


Edit: I actually believe we should never deprecate string lookups, as this would break the automatic inferral, when decorators can change signatures, i.e.:

import Service, { inject as service } from '@ember/service';

class FooService extends Service {
  @service bar;
}

@buschtoens

Copy link
Copy Markdown
Contributor

One further observation: The Ember Resolver / Container system is a bit of magic in the background. You don't always know where the backing injectee class is actually located or it might not be accessible to the code you are authoring.

There's also nothing preventing you from registering the same class with multiple names or even generating the names at runtime.

Admittedly these are uncommon edge cases.

@lougreenwood

lougreenwood commented Jun 15, 2019 •

Copy link
Copy Markdown

Also, by requiring explicit class name use, we're coupling the class to a specific service, but this shouldn't be a concern of the class:

Dependency injection is one form of the broader technique of inversion of control. The client delegates the responsibility of providing its dependencies to external code (the injector). The client is not allowed to call the injector code;[2] it is the injecting code that constructs the services and calls the client to inject them. This means the client code does not need to know about the injecting code, how to construct the services or even which actual services it is using; the client only needs to know about the intrinsic interfaces of the services because these define how the client may use the services. This separates the responsibilities of use and construction.
https://en.wikipedia.org/wiki/Dependency_injection

I mean, if we're going to import the ClassName, why not instantiate the service singleton and skip the service() container lookup all together.... But we all know that's a bad idea as it removes IoC.

So whilst I like the look of this as purely a nicer way to write TS classes in Ember right now - it's not really DI any more since the explicit class name is required (no more IoC).

So it seems that if the goal is to improve typing in TS, proper TS support for decorators will give us that.

For newbies that get confused by strings, maybe we need to better teach the newbies about DI and why a string name is about as explicit & accurate a DI lookup name should be to maintain proper separation.

@buschtoens

buschtoens commented Jun 15, 2019 •

Copy link
Copy Markdown
Contributor

@lougreenwood I totally agree with the point you're making regarding isolation of concerns.

However, I think @NullVoxPopuli was not aiming at better TypeScript support, but instead better "cmd+clickability" support for generic JS IDEs / users that don't use TypeScript.

Please correct me, if I am wrong.

@lougreenwood

lougreenwood commented Jun 15, 2019 •

Copy link
Copy Markdown

yeah - you're right, I was getting ahead of myself - sorry :D

But IMO, we also shouldn't start hacking apart established patterns for nicer IDE support - our solution should "work with the patterns" as well as "using the platform".

So if I understand JS & IDEs correctly... Since JS is not typed, and by it's nature DI de-couples - then there's no "platform" mechanism which is true to DI other than typing (and decorators changing function signature) which allows nice IDE integration?

@NullVoxPopuli

NullVoxPopuli commented Jun 15, 2019 •

Copy link
Copy Markdown
Contributor Author

@webark the class would be an import of the service itself :)

import Component from '@glimmer/components';
import { inject as service } from '@ember/services';
import MyService from 'appmame/services/my-service';

export default class extends Component {
  @service(MyService) myService;
}

:)

@NullVoxPopuli

Copy link
Copy Markdown
Contributor Author

@buschtoens the registry pattern could be used with classes as keys, couldn't it?

@NullVoxPopuli

Copy link
Copy Markdown
Contributor Author

then there's no "platform" mechanism which is true to DI

If only we had interfaces we could use instead :)

@NullVoxPopuli NullVoxPopuli changed the title Explicit Dependency Injection Explicit Service Injection Jun 15, 2019
@NullVoxPopuli

Copy link
Copy Markdown
Contributor Author

Renamed RFC due to technicality in DI definition

@buschtoens

Copy link
Copy Markdown
Contributor

the registry pattern could be used with classes as keys, couldn't it?

@NullVoxPopuli Yes, of course it could. But that's not the point I was trying to make. 🙂

Switching to a class-based registry / decorator and deprecating the string-based one, means that the future TypeScript ergonomics will be much worse, because you can't any more use the property name to infer the injection, as show in #502 (comment).

@NullVoxPopuli

Copy link
Copy Markdown
Contributor Author

Gotchya, so string lookup stays :)

@webark

webark commented Jun 15, 2019

Copy link
Copy Markdown

the class would be an import of the service itself

Thanks for clearing that up!

So there’s a pattern where you extend a dependencies service, to either overwrite or extend the dependent service.

When this is done, all of your existing references are updated.

With direct imports, would you always import a dependents service from the addons merged “app” space, even if it doesn’t exist? Or would you need to go and update all of your imports where you had imported them from the depended addon?

@NullVoxPopuli

Copy link
Copy Markdown
Contributor Author

would you always import a dependents service from the addons merged “app” space, even if it doesn’t exist? Or would you need to go and update all of your imports where you had imported them from the depended addon?

it should resolve to the same thing in both scenarios, afaik

@buschtoens

buschtoens commented Jun 16, 2019 •

Copy link
Copy Markdown
Contributor

With direct imports, would you always import a dependents service from the addons merged “app” space, even if it doesn’t exist? Or would you need to go and update all of your imports where you had imported them from the depended addon?

it should resolve to the same thing in both scenarios, afaik

An addon that has a service re-export in its app tree would make the service available in the host app, via the resolver, however the file would not be physically "there", meaning that "cmd+click" would fail, while the import would work at runtime.


I don't want to explode the scope here, but this segways into another interesting problem: What is the "official" way (pre and post this RFC) to override / clobber an addon's service (from another addon possibly)?

One way is using ember-addon.after in the package.json of the overriding addon to ensure that its app tree clobbers the app tree of the overridden addon. You could do the same from the host app as well.

One major hazard of this approach is emberjs/ember-cli-babel#240: If you use a file extension other than js, the clobbering might fail non-deterministically.

@NullVoxPopuli

NullVoxPopuli commented Jun 16, 2019 •

Copy link
Copy Markdown
Contributor Author

I don't want to explode the scope here, but this segways into another interesting problem: What is the "official" way (pre and post this RFC) to override / clobber an addon's service (from another addon possibly)?

maybe this RFC should be held off until embroider ships ;)
(though, I need to see if embroider would actually fix that problem)

but, I don't think we should continue to have clobbering of services. It's hard to debug.
if I import a service form an addon, I want that to be the actual location so I can ctrl/cmd click it and see what it is.

@webark

webark commented Jun 16, 2019

Copy link
Copy Markdown

An addon that has a service re-export in its app tree would make the service available in the host app, via the resolver, however the file would not be physically "there", meaning that "cmd+click" would fail, while the import would work at runtime.

this just goes against the main motivation of “enable "go to definition" support from service definitions so developers can more easily discover the where and how their service is defined.”

For using services in addons, it seems just as magical also, and more confusing around “is this a singleton” especially if you could import the same service from the invisible “app” space, and where it lives in the addon’s “addon” space in the same app.

@mehulkar

Copy link
Copy Markdown

This RFC should also probably provide some text about how to register/inject services in component rendering tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@NullVoxPopuli

Copy link
Copy Markdown
Contributor Author

you can try out this RFC with:

Co-authored-by: NullVoxPopuli <199018+NullVoxPopuli@users.noreply.github.com>
* Fix typos and inconsistencies in RFC 502

Typos and grammar, plus these content fixes:

- the service() sketch read `name` instead of `nameOrClass`
- say how a thunk is told apart from a class key
- the ember-intl note implied that lookup finds subclasses;
  the app must register its subclass before the first lookup
- the decorator form still needs a type annotation; only the
  non-decorator form infers the field type
- registry is named `Registry`, not `DIRegistry`
- the cookie example used a WebExtension API; use document.cookie
- missing imports, unused `test` imports, an undefined `cleanup`,
  and a Counter constructor that the unit test calls without an owner
- free-function lookup/register calls match the owner methods
- the appendix pointed to a missing "Implementation notes" section
- add an unresolved question for abstract keys with no registration

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fix the nollm findings in RFC 502

Unwrap hard-wrapped prose, split long sentences, drop "today",
and give each file in a code example its own block with the
file name above it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Use plainer wording in the later RFC 502 edits

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Apply suggestion from @NullVoxPopuli

---------

Co-authored-by: NullVoxPopuli <199018+NullVoxPopuli@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

- more verbose
- disruptive for libraries providing services
- the non-decorator form loses lazy instantiation

@NullVoxPopuli NullVoxPopuli Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this can be solved if we add a lazy() utility to add this capability back -- so:

prop = lazy(service(this, Key)) // wraps in a proxy

(not for this RFC)

but folks can use a getter to get lazy instantiation without another utility


Not available today, since `Service` has to be created through the container.

## How we teach this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

* RFC 502: overrideService, service(owner, Key), service protocol

Address the 2026-11-16 review comments:

- Override a class key with `overrideService(owner, Key, Impl)` from
  `@ember/service`. `owner.register` and the application instance do
  not change.
- Look up a class key with `service(owner, Key)`, not `owner.lookup`.
- Add "what can be a service": the rules for keys and implementations.
- Drawbacks: a getter restores lazy instantiation. A `lazy()` utility
  is left to a future RFC.
- How we teach this: link guides-source#2237.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* RFC 502: factories with create() are keys and implementations

A key or an implementation can be a class, or anything with a
`create(props)` method: a plain object or a function. `create` is
checked first, so an arrow function with `create` is a factory, not a
thunk. This is the same factory protocol that `owner.register` already
accepts on the string path.

- `create` must return an object. An override of a class key must
  return an instance of the key.
- The hierarchy check becomes "inherits from the key", which covers
  `class B extends A` and `{ __proto__: key, create() {} }`.
- `Key<T>` is a class or a `Factory<T>`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* RFC 502: remove implementation details

Keep the behavior and the public API, and leave the mechanism to the
implementation:

- Remove the `lookupByClass` pseudo-code, the `prototype` and
  `isPrototypeOf` checks, and the internal predicates.
- Remove the `InternalFactoryManager`, `WeakMap`, and
  `associateDestroyableChild` details.
- Remove the list of what `Service` must contain, and the polyfill's
  babel plugin behavior.
- The appendix says that storage is not prescribed, names the
  `WeakMap` approach as one option, and links the polyfill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Apply suggestion from @NullVoxPopuli

---------

Co-authored-by: NullVoxPopuli <199018+NullVoxPopuli@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: NullVoxPopuli <199018+NullVoxPopuli@users.noreply.github.com>
NullVoxPopuli and others added 2 commits November 17, 2026 11:44
A plain object with create() has no class hierarchy to protect,
and code that uses one already opts out of the checks a class
gives. Any key can override it. TypeScript still checks the type.

Co-authored-by: NullVoxPopuli <199018+NullVoxPopuli@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

@NullVoxPopuli NullVoxPopuli left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

posting answers to the questions on here before I clear out the unresalved questions section


## Unresolved Questions

- Does `@ember/service` export a way to ask whether a key has an override, or whether a key was already resolved on an owner?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, and I don't believe there is a need to


- Does `@ember/service` export a way to ask whether a key has an override, or whether a key was already resolved on an owner?

- Should looking up an abstract key with no override throw? At runtime it builds an instance of the abstract class, which has none of the abstract members.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, this is up to the implementor of the abstract class to figure out (until JavaScript itself gets better tooling / behavior around this)


- Should looking up an abstract key with no override throw? At runtime it builds an instance of the abstract class, which has none of the abstract members.

- What does the Ember Inspector show for a class-keyed instance in a production build, where `Klass.name` is minified?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the minified class name -- same as other classes (mostly components)


- What does the Ember Inspector show for a class-keyed instance in a production build, where `Klass.name` is minified?

- Does the `@service` decorator need to keep supporting assignment (`this.myService = stub`)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, this isn't even supported today and is an accident

@runspired runspired left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having been a rather vocal detractor / devil's advocate on this RFC I just want to weigh in and say thanks to Preston for pushing it forward. I think it's ready. I've suggested adding a few examples that will clear up some powerful patterns I think this enables so that they are more discoverable, but no blocking feedback.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Final Comment Period S-Exploring In the Exploring RFC Stage

Projects

None yet

Development

Successfully merging this pull request may close these issues.