Repository navigation
Explicit Service Injection - #502
NullVoxPopuli wants to merge 27 commits into
Conversation
|
@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? |
|
hi @NullVoxPopuli , 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('...');
} |
|
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 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: |
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). |
|
@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;
} |
|
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. |
|
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:
I mean, if we're going to import the 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. |
|
@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. |
|
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? |
|
@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;
}:) |
|
@buschtoens the registry pattern could be used with classes as keys, couldn't it? |
If only we had interfaces we could use instead :) |
|
Renamed RFC due to technicality in DI definition |
@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). |
|
Gotchya, so string lookup stays :) |
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? |
it should resolve to the same thing in both scenarios, afaik |
An addon that has a service re-export in its 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 One major hazard of this approach is emberjs/ember-cli-babel#240: If you use a file extension other than |
maybe this RFC should be held off until embroider ships ;) but, I don't think we should continue to have clobbering of services. It's hard to debug. |
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. |
|
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>
|
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
* 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>
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
left a comment
There was a problem hiding this comment.
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? |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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? |
There was a problem hiding this comment.
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`)? |
There was a problem hiding this comment.
no, this isn't even supported today and is an accident
runspired
left a comment
There was a problem hiding this comment.
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.
To view rendered:
Link at the time of updating the PR description:
https://github.com/NullVoxPopuli/rfcs/blob/explicit-dependency-injection/text/0502-explicit-dependency-injection.md