Skip to content

Commit

Permalink
feat(core): Adds DI support for providedIn: 'platform'|'any' (#32154)
Browse files Browse the repository at this point in the history
Extend the vocabulary of the `providedIn` to also include  `'platform'` and `'any'`` scope.
```
@Injectable({
  providedId: 'platform', // tree shakable injector for platform injector
})
class MyService {...}
```

PR Close #32154
  • Loading branch information
mhevery committed Aug 30, 2019
1 parent 8a47b48 commit 77c382c
Show file tree
Hide file tree
Showing 16 changed files with 138 additions and 64 deletions.
2 changes: 1 addition & 1 deletion packages/core/src/core_private_export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export {ChangeDetectorStatus as ɵChangeDetectorStatus, isDefaultChangeDetection
export {Console as ɵConsole} from './console';
export {inject, setCurrentInjector as ɵsetCurrentInjector, ɵɵinject} from './di/injector_compatibility';
export {getInjectableDef as ɵgetInjectableDef, ɵɵInjectableDef, ɵɵInjectorDef} from './di/interface/defs';
export {APP_ROOT as ɵAPP_ROOT} from './di/scope';
export {INJECTOR_SCOPE as ɵINJECTOR_SCOPE} from './di/scope';
export {DEFAULT_LOCALE_ID as ɵDEFAULT_LOCALE_ID} from './i18n/localization';
export {ivyEnabled as ɵivyEnabled} from './ivy_switch';
export {ComponentFactory as ɵComponentFactory} from './linker/component_factory';
Expand Down
22 changes: 14 additions & 8 deletions packages/core/src/di/injectable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,11 @@ export interface InjectableDecorator {
*
*/
(): TypeDecorator;
(options?: {providedIn: Type<any>| 'root' | null}&InjectableProvider): TypeDecorator;
(options?: {providedIn: Type<any>| 'root' | 'platform' | 'any' | null}&
InjectableProvider): TypeDecorator;
new (): Injectable;
new (options?: {providedIn: Type<any>| 'root' | null}&InjectableProvider): Injectable;
new (options?: {providedIn: Type<any>| 'root' | 'platform' | 'any' | null}&
InjectableProvider): Injectable;
}

/**
Expand All @@ -64,10 +66,14 @@ export interface Injectable {
/**
* Determines which injectors will provide the injectable,
* by either associating it with an @NgModule or other `InjectorType`,
* or by specifying that this injectable should be provided in the
* 'root' injector, which will be the application-level injector in most apps.
* or by specifying that this injectable should be provided in the:
* - 'root' injector, which will be the application-level injector in most apps.
* - 'platform' injector, which would be the special singleton platform injector shared by all
* applications on the page.
* - 'any` injector, which would be the injector which receives the resolution. (Note this only
* works on NgModule Injectors and not on Element Injector)
*/
providedIn?: Type<any>|'root'|null;
providedIn?: Type<any>|'root'|'platform'|'any'|null;
}

/**
Expand All @@ -90,9 +96,9 @@ export interface InjectableType<T> extends Type<T> { ngInjectableDef: ɵɵInject
/**
* Supports @Injectable() in JIT mode for Render2.
*/
function render2CompileInjectable(
injectableType: Type<any>,
options?: {providedIn?: Type<any>| 'root' | null} & InjectableProvider): void {
function render2CompileInjectable(injectableType: Type<any>, options?: {
providedIn?: Type<any>| 'root' | 'platform' | 'any' | null
} & InjectableProvider): void {
if (options && options.providedIn !== undefined && !getInjectableDef(injectableType)) {
(injectableType as InjectableType<any>).ngInjectableDef = ɵɵdefineInjectable({
token: injectableType,
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/di/injection_token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export class InjectionToken<T> {
readonly ngInjectableDef: never|undefined;

constructor(protected _desc: string, options?: {
providedIn?: Type<any>| 'root' | null,
providedIn?: Type<any>| 'root' | 'platform' | 'any' | null,
factory: () => T
}) {
this.ngInjectableDef = undefined;
Expand Down
48 changes: 38 additions & 10 deletions packages/core/src/di/injector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ import {stringify} from '../util/stringify';

import {resolveForwardRef} from './forward_ref';
import {InjectionToken} from './injection_token';
import {INJECTOR, NG_TEMP_TOKEN_PATH, NullInjector, THROW_IF_NOT_FOUND, USE_VALUE, catchInjectorError, formatError, ɵɵinject} from './injector_compatibility';
import {ɵɵdefineInjectable} from './interface/defs';
import {INJECTOR, NG_TEMP_TOKEN_PATH, NullInjector, THROW_IF_NOT_FOUND, USE_VALUE, catchInjectorError, formatError, setCurrentInjector, ɵɵinject} from './injector_compatibility';
import {getInjectableDef, ɵɵdefineInjectable} from './interface/defs';
import {InjectFlags} from './interface/injector';
import {ConstructorProvider, ExistingProvider, FactoryProvider, StaticClassProvider, StaticProvider, ValueProvider} from './interface/provider';
import {Inject, Optional, Self, SkipSelf} from './metadata';
import {createInjector} from './r3_injector';
import {INJECTOR_SCOPE} from './scope';

export function INJECTOR_IMPL__PRE_R3__(
providers: StaticProvider[], parent: Injector | undefined, name: string) {
Expand Down Expand Up @@ -124,8 +125,9 @@ const NO_NEW_LINE = 'ɵ';
export class StaticInjector implements Injector {
readonly parent: Injector;
readonly source: string|null;
readonly scope: string|null;

private _records: Map<any, Record>;
private _records: Map<any, Record|null>;

constructor(
providers: StaticProvider[], parent: Injector = Injector.NULL, source: string|null = null) {
Expand All @@ -136,17 +138,37 @@ export class StaticInjector implements Injector {
Injector, <Record>{token: Injector, fn: IDENT, deps: EMPTY, value: this, useNew: false});
records.set(
INJECTOR, <Record>{token: INJECTOR, fn: IDENT, deps: EMPTY, value: this, useNew: false});
recursivelyProcessProviders(records, providers);
this.scope = recursivelyProcessProviders(records, providers);
}

get<T>(token: Type<T>|InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): T;
get(token: any, notFoundValue?: any): any;
get(token: any, notFoundValue?: any, flags: InjectFlags = InjectFlags.Default): any {
const record = this._records.get(token);
const records = this._records;
let record = records.get(token);
if (record === undefined) {
// This means we have never seen this record, see if it is tree shakable provider.
const injectableDef = getInjectableDef(token);
if (injectableDef) {
const providedIn = injectableDef && injectableDef.providedIn;
if (providedIn === 'any' || providedIn != null && providedIn === this.scope) {
records.set(
token, record = resolveProvider(
{provide: token, useFactory: injectableDef.factory, deps: EMPTY}));
}
}
if (record === undefined) {
// Set record to null to make sure that we don't go through expensive lookup above again.
records.set(token, null);
}
}
let lastInjector = setCurrentInjector(this);
try {
return tryResolveToken(token, record, this._records, this.parent, notFoundValue, flags);
return tryResolveToken(token, record, records, this.parent, notFoundValue, flags);
} catch (e) {
return catchInjectorError(e, token, 'StaticInjectorError', this.source);
} finally {
setCurrentInjector(lastInjector);
}
}

Expand Down Expand Up @@ -203,13 +225,15 @@ function multiProviderMixError(token: any) {
return staticError('Cannot mix multi providers and regular providers', token);
}

function recursivelyProcessProviders(records: Map<any, Record>, provider: StaticProvider) {
function recursivelyProcessProviders(records: Map<any, Record>, provider: StaticProvider): string|
null {
let scope: string|null = null;
if (provider) {
provider = resolveForwardRef(provider);
if (provider instanceof Array) {
// if we have an array recurse into the array
for (let i = 0; i < provider.length; i++) {
recursivelyProcessProviders(records, provider[i]);
scope = recursivelyProcessProviders(records, provider[i]) || scope;
}
} else if (typeof provider === 'function') {
// Functions were supported in ReflectiveInjector, but are not here. For safety give useful
Expand Down Expand Up @@ -244,15 +268,19 @@ function recursivelyProcessProviders(records: Map<any, Record>, provider: Static
if (record && record.fn == MULTI_PROVIDER_FN) {
throw multiProviderMixError(token);
}
if (token === INJECTOR_SCOPE) {
scope = resolvedProvider.value;
}
records.set(token, resolvedProvider);
} else {
throw staticError('Unexpected provider', provider);
}
}
return scope;
}

function tryResolveToken(
token: any, record: Record | undefined, records: Map<any, Record>, parent: Injector,
token: any, record: Record | undefined | null, records: Map<any, Record|null>, parent: Injector,
notFoundValue: any, flags: InjectFlags): any {
try {
return resolveToken(token, record, records, parent, notFoundValue, flags);
Expand All @@ -272,7 +300,7 @@ function tryResolveToken(
}

function resolveToken(
token: any, record: Record | undefined, records: Map<any, Record>, parent: Injector,
token: any, record: Record | undefined | null, records: Map<any, Record|null>, parent: Injector,
notFoundValue: any, flags: InjectFlags): any {
let value;
if (record && !(flags & InjectFlags.SkipSelf)) {
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/di/interface/defs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export interface ɵɵInjectableDef<T> {
* - `null`, does not belong to any injector. Must be explicitly listed in the injector
* `providers`.
*/
providedIn: InjectorType<any>|'root'|'any'|null;
providedIn: InjectorType<any>|'root'|'platform'|'any'|null;

/**
* The token to which this definition belongs.
Expand Down Expand Up @@ -140,7 +140,7 @@ export interface InjectorTypeWithProviders<T> {
*/
export function ɵɵdefineInjectable<T>(opts: {
token: unknown,
providedIn?: Type<any>| 'root' | 'any' | null,
providedIn?: Type<any>| 'root' | 'platform' | 'any' | null,
factory: () => T,
}): never {
return ({
Expand Down
21 changes: 13 additions & 8 deletions packages/core/src/di/r3_injector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {INJECTOR, NG_TEMP_TOKEN_PATH, NullInjector, THROW_IF_NOT_FOUND, USE_VALU
import {InjectorType, InjectorTypeWithProviders, getInheritedInjectableDef, getInjectableDef, getInjectorDef, ɵɵInjectableDef} from './interface/defs';
import {InjectFlags} from './interface/injector';
import {ClassProvider, ConstructorProvider, ExistingProvider, FactoryProvider, StaticClassProvider, StaticProvider, TypeProvider, ValueProvider} from './interface/provider';
import {APP_ROOT} from './scope';
import {INJECTOR_SCOPE} from './scope';



Expand Down Expand Up @@ -84,8 +84,10 @@ export function createInjector(
export class R3Injector {
/**
* Map of tokens to records which contain the instances of those tokens.
* - `null` value implies that we don't have the record. Used by tree-shakable injectors
* to prevent further searches.
*/
private records = new Map<Type<any>|InjectionToken<any>, Record<any>>();
private records = new Map<Type<any>|InjectionToken<any>, Record<any>|null>();

/**
* The transitive set of `InjectorType`s which define this injector.
Expand All @@ -101,7 +103,7 @@ export class R3Injector {
* Flag indicating this injector provides the APP_ROOT_SCOPE token, and thus counts as the
* root scope.
*/
private readonly isRootInjector: boolean;
private readonly scope: 'root'|'platform'|null;

readonly source: string|null;

Expand Down Expand Up @@ -129,7 +131,8 @@ export class R3Injector {

// Detect whether this injector has the APP_ROOT_SCOPE token and thus should provide
// any injectable scoped to APP_ROOT_SCOPE.
this.isRootInjector = this.records.has(APP_ROOT);
const record = this.records.get(INJECTOR_SCOPE);
this.scope = record != null ? record.value : null;

// Eagerly instantiate the InjectorType classes themselves.
this.injectorDefTypes.forEach(defType => this.get(defType));
Expand Down Expand Up @@ -170,7 +173,7 @@ export class R3Injector {
// Check for the SkipSelf flag.
if (!(flags & InjectFlags.SkipSelf)) {
// SkipSelf isn't set, check if the record belongs to this injector.
let record: Record<T>|undefined = this.records.get(token);
let record: Record<T>|undefined|null = this.records.get(token);
if (record === undefined) {
// No record, but maybe the token is scoped to this injector. Look for an ngInjectableDef
// with a scope matching this injector.
Expand All @@ -179,11 +182,13 @@ export class R3Injector {
// Found an ngInjectableDef and it's scoped to this injector. Pretend as if it was here
// all along.
record = makeRecord(injectableDefOrInjectorDefFactory(token), NOT_YET);
this.records.set(token, record);
} else {
record = null;
}
this.records.set(token, record);
}
// If a record was found, get the instance for it and return it.
if (record !== undefined) {
if (record != null /* NOT null || undefined */) {
return this.hydrate(token, record);
}
}
Expand Down Expand Up @@ -389,7 +394,7 @@ export class R3Injector {
if (!def.providedIn) {
return false;
} else if (typeof def.providedIn === 'string') {
return def.providedIn === 'any' || (def.providedIn === 'root' && this.isRootInjector);
return def.providedIn === 'any' || (def.providedIn === this.scope);
} else {
return this.injectorDefTypes.has(def.providedIn);
}
Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/di/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,4 @@ import {InjectionToken} from './injection_token';
* as a root scoped injector when processing requests for unknown tokens which may indicate
* they are provided in the root scope.
*/
export const APP_ROOT = new InjectionToken<boolean>(
'The presence of this token marks an injector as being the root injector.');
export const INJECTOR_SCOPE = new InjectionToken<'root'|'platform'|null>('Set Injector scope.');
2 changes: 1 addition & 1 deletion packages/core/src/view/entrypoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ function cloneNgModuleDefinition(def: NgModuleDefinition): NgModuleDefinition {

return {
factory: def.factory,
isRoot: def.isRoot, providers, modules, providersByKey,
scope: def.scope, providers, modules, providersByKey,
};
}

Expand Down
15 changes: 8 additions & 7 deletions packages/core/src/view/ng_module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {resolveForwardRef} from '../di/forward_ref';
import {Injector} from '../di/injector';
import {INJECTOR, setCurrentInjector} from '../di/injector_compatibility';
import {getInjectableDef, ɵɵInjectableDef} from '../di/interface/defs';
import {APP_ROOT} from '../di/scope';
import {INJECTOR_SCOPE} from '../di/scope';
import {NgModuleRef} from '../linker/ng_module_factory';
import {newArray} from '../util/array_utils';
import {stringify} from '../util/stringify';
Expand Down Expand Up @@ -42,11 +42,11 @@ export function moduleProvideDef(
export function moduleDef(providers: NgModuleProviderDef[]): NgModuleDefinition {
const providersByKey: {[key: string]: NgModuleProviderDef} = {};
const modules = [];
let isRoot: boolean = false;
let scope: 'root'|'platform'|null = null;
for (let i = 0; i < providers.length; i++) {
const provider = providers[i];
if (provider.token === APP_ROOT && provider.value === true) {
isRoot = true;
if (provider.token === INJECTOR_SCOPE) {
scope = provider.value;
}
if (provider.flags & NodeFlags.TypeNgModule) {
modules.push(provider.token);
Expand All @@ -60,7 +60,7 @@ export function moduleDef(providers: NgModuleProviderDef[]): NgModuleDefinition
providersByKey,
providers,
modules,
isRoot,
scope: scope,
};
}

Expand Down Expand Up @@ -134,8 +134,9 @@ function moduleTransitivelyPresent(ngModule: NgModuleData, scope: any): boolean
}

function targetsModule(ngModule: NgModuleData, def: ɵɵInjectableDef<any>): boolean {
return def.providedIn != null && (moduleTransitivelyPresent(ngModule, def.providedIn) ||
def.providedIn === 'root' && ngModule._def.isRoot);
const providedIn = def.providedIn;
return providedIn != null && (providedIn === 'any' || providedIn === ngModule._def.scope ||
moduleTransitivelyPresent(ngModule, providedIn));
}

function _createProviderInstance(ngModule: NgModuleData, providerDef: NgModuleProviderDef): any {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/view/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export interface NgModuleDefinition extends Definition<NgModuleDefinitionFactory
providers: NgModuleProviderDef[];
providersByKey: {[tokenKey: string]: NgModuleProviderDef};
modules: any[];
isRoot: boolean;
scope: 'root'|'platform'|null;
}

export interface NgModuleDefinitionFactory extends DefinitionFactory<NgModuleDefinition> {}
Expand Down
32 changes: 32 additions & 0 deletions packages/core/test/acceptance/di_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import {CommonModule} from '@angular/common';
import {Attribute, ChangeDetectorRef, Component, Directive, ElementRef, EventEmitter, Host, HostBinding, INJECTOR, Inject, Injectable, InjectionToken, Injector, Input, LOCALE_ID, ModuleWithProviders, NgModule, Optional, Output, Pipe, PipeTransform, Self, SkipSelf, TemplateRef, ViewChild, ViewContainerRef, forwardRef, ɵDEFAULT_LOCALE_ID as DEFAULT_LOCALE_ID} from '@angular/core';
import {ɵINJECTOR_SCOPE} from '@angular/core/src/core';
import {ViewRef} from '@angular/core/src/render3/view_ref';
import {TestBed} from '@angular/core/testing';
import {ivyEnabled, onlyInIvy} from '@angular/private/testing';
Expand Down Expand Up @@ -866,6 +867,37 @@ describe('di', () => {
});
});

describe('Tree shakable injectors', () => {
it('should support tree shakable injectors scopes', () => {
@Injectable({providedIn: 'any'})
class AnyService {
constructor(public injector: Injector) {}
}

@Injectable({providedIn: 'root'})
class RootService {
constructor(public injector: Injector) {}
}

@Injectable({providedIn: 'platform'})
class PlatformService {
constructor(public injector: Injector) {}
}

const testBedInjector: Injector = TestBed.get(Injector);
const childInjector = Injector.create([], testBedInjector);

const anyService = childInjector.get(AnyService);
expect(anyService.injector).toBe(childInjector);

const rootService = childInjector.get(RootService);
expect(rootService.injector.get(ɵINJECTOR_SCOPE)).toBe('root');

const platformService = childInjector.get(PlatformService);
expect(platformService.injector.get(ɵINJECTOR_SCOPE)).toBe('platform');
});
});

describe('service injection', () => {

it('should create instance even when no injector present', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[
{
"name": "APP_ROOT"
"name": "INJECTOR_SCOPE"
},
{
"name": "CIRCULAR"
Expand Down

0 comments on commit 77c382c

Please sign in to comment.