inversify#interfaces TypeScript Examples
The following examples show how to use
inversify#interfaces.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: inject.tsx From mo360-ftk with MIT License | 6 votes |
export default function inject(serviceId?: string | symbol | interfaces.Newable<{}>) {
return (target: any, propertyKey: string) => {
Object.defineProperty(target, propertyKey, {
enumerable: true,
configurable: true,
get() {
if (!this.props.container) {
throw new Error(
`Can't access injected property ${propertyKey} on ${target}, did you forget to wrap your component in withDi()?`,
);
}
const container = this.props.container as IDiContainer;
if (serviceId !== undefined) {
if (container.isBound(serviceId)) {
return container.get(serviceId);
} else {
throw new Error(
`Can't inject ${propertyKey} as no dependency binding for ${serviceId.toString()} could be found.`,
);
}
} else {
const keyFromMetadata = Reflect.getMetadata('design:type', target, propertyKey);
if (!keyFromMetadata) {
throw new Error(
`Can't inject ${propertyKey} as no metadata could be found. Did you import reflect-metadata?`,
);
}
if (!container.isBound(keyFromMetadata)) {
throw new Error(
`Can't inject ${propertyKey} as no binding for type ${keyFromMetadata} was found. Did you register it in the DiContainer?`,
);
}
return container.get(keyFromMetadata);
}
},
});
};
}
Example #2
Source File: collector.ts From reactant with MIT License | 6 votes |
export function createCollector(ServiceIdentifiers: ServiceIdentifiersMap) {
return (planAndResolve: interfaces.Next): interfaces.Next => (
args: interfaces.NextArgs
) => {
const nextContextInterceptor = args.contextInterceptor;
const contextInterceptor = (context: interfaces.Context) => {
lookupServiceIdentifiers(context.plan.rootRequest, ServiceIdentifiers);
return nextContextInterceptor(context);
};
const result = planAndResolve({
...args,
contextInterceptor,
});
return result;
};
}
Example #3
Source File: collector.ts From reactant with MIT License | 6 votes |
function lookupServiceIdentifiers(
request: interfaces.Request,
ServiceIdentifiers: ServiceIdentifiersMap
) {
// It is used to perform the required dependency collection when dynamically importing modules.
if (!ServiceIdentifiers.has(request.serviceIdentifier)) {
ServiceIdentifiers.set(request.serviceIdentifier, []);
}
const depServiceIdentifier = request.childRequests.map(
(childRequest) => childRequest.serviceIdentifier
);
ServiceIdentifiers.set(request.serviceIdentifier, depServiceIdentifier);
if (request.childRequests.length === 0) return;
request.childRequests.forEach((childRequest) => {
lookupServiceIdentifiers(childRequest, ServiceIdentifiers);
});
}
Example #4
Source File: createContainer.ts From reactant with MIT License | 6 votes |
function autoBindModules() {
return new ContainerModule(
(
bind: interfaces.Bind,
unbind: interfaces.Unbind,
isBound: interfaces.IsBound
) => {
const provideMeta = getMetadata(METADATA_KEY.provide);
const optionalMeta = getMetadata(METADATA_KEY.optional);
for (const [identifier, provide] of provideMeta) {
// default injection without optional module.
if (
(!optionalMeta.has(identifier) ||
lookupOptionalIdentifier(identifier)) &&
!isBound(identifier)
) {
bind(identifier).to(provide);
}
}
}
);
}
Example #5
Source File: repositories.bind.ts From nodejs-angular-typescript-boilerplate with Apache License 2.0 | 6 votes |
export default async function bindRepositories(
container: interfaces.Container
) {
const entityTypes = [
REPOSITORY_TYPES.UserEntity
];
const repositories = await getRepositories<any>([UserEntity]);
repositories.forEach((repository, i) => {
const repositoryType = entityTypes[i];
container.bind<Repository<any>>(repositoryType).toConstantValue(repository);
});
return repositories;
}
Example #6
Source File: middleware.bind.ts From nodejs-angular-typescript-boilerplate with Apache License 2.0 | 6 votes |
export default async function bindMiddlewares(
container: interfaces.Container
) {
const middlewares = [
{
type: MIDDLEWARE_TYPES.AuthenticatedMiddleware,
entity: AuthenticateMiddleware
},
{
type: MIDDLEWARE_TYPES.RequiredMiddleware,
entity: RequiredLoginMiddleware
}
];
middlewares.forEach(middleware => {
container.bind(middleware.type).to(middleware.entity);
});
}
Example #7
Source File: Hooks.tsx From mo360-ftk with MIT License | 6 votes |
export function useFromDi<T>(serviceId: string | symbol | interfaces.Newable<T>): T {
const diContainer = React.useContext<IDiContainer>(diContext);
if (!diContainer.isBound(serviceId)) {
throw new Error(
`Could not inject ${serviceId.toString()} as it is currently not bound in this scope. Are you missing a Provider?`,
);
}
return diContainer.get<T>(serviceId);
}
Example #8
Source File: findBoundContainer.tsx From mo360-ftk with MIT License | 6 votes |
/**
* Walks up a container hierarchy until the container that originally bound a
* dependency is found. This is especially usefull for .rebind() and .unbind() as
* those have to be performed on the container originally used to .bind() a dependency.
*/
export function findBoundContainer(
container: IDiContainer,
serviceId: string | symbol | interfaces.Newable<{}>,
): IDiContainer {
if (!container.isBound(serviceId) || !container.parent) {
throw new Error(`Identifier ${serviceId.toString()} not bound in container hierarchy!`);
}
if (container.parent.isBound(serviceId) === false) {
return container;
} else {
return findBoundContainer(container.parent, serviceId);
}
}
Example #9
Source File: inversify.config.ts From vscode-dbt-power-user with MIT License | 6 votes |
container
.bind<interfaces.Factory<DBTProject>>("Factory<DBTProject>")
.toFactory<DBTProject>((context: interfaces.Context) => {
return (
path: Uri,
_onManifestChanged: EventEmitter<ManifestCacheChangedEvent>
) => {
const { container } = context;
return new DBTProject(
container.get(DBTProjectContainer),
container.get(SourceFileWatchersFactory),
container.get(DBTProjectLogFactory),
container.get(TargetWatchersFactory),
container.get(DBTCommandFactory),
container.get(DBTTerminal),
path,
_onManifestChanged
);
};
});
Example #10
Source File: inversify.config.ts From vscode-dbt-power-user with MIT License | 6 votes |
container
.bind<interfaces.Factory<DBTWorkspaceFolder>>("Factory<DBTWorkspaceFolder>")
.toFactory<DBTWorkspaceFolder>((context: interfaces.Context) => {
return (
workspaceFolder: WorkspaceFolder,
_onManifestChanged: EventEmitter<ManifestCacheChangedEvent>
) => {
const { container } = context;
return new DBTWorkspaceFolder(
container.get("Factory<DBTProject>"),
workspaceFolder,
_onManifestChanged,
);
};
});
Example #11
Source File: auto-bind.ts From malagu with MIT License | 6 votes |
function resolveConstant(metadata: ConstantOption, bind: interfaces.Bind, rebind: interfaces.Rebind): void {
const ids = Array.isArray(metadata.id) ? metadata.id : [ metadata.id ];
const id = ids.shift();
if (metadata.rebind) {
rebind(id!).toConstantValue(metadata.constantValue);
} else {
bind(id!).toConstantValue(metadata.constantValue);
}
for (const item of ids) {
bind(item!).toService(id!);
}
}
Example #12
Source File: auto-bind.ts From malagu with MIT License | 6 votes |
function resolve(metadata: ComponentMetadata, bind: interfaces.Bind, rebind: interfaces.Rebind): void {
let mid: any;
const { ids, scope, name, tag, when, proxy, onActivation, target } = metadata;
const id = ids.shift()!;
mid = metadata.rebind ? rebind(id).to(target) : bind(id).to(target);
if (scope === Scope.Singleton) {
mid = mid.inSingletonScope();
} else if (scope === Scope.Transient) {
mid = mid.inTransientScope();
}
if (name) {
mid = mid.whenTargetNamed(name);
} else if (tag) {
mid = mid.whenTargetTagged(tag.tag, tag.value);
} else if (metadata.default) {
mid = mid.whenTargetIsDefault();
} else if (when) {
mid = mid.when(when);
}
if (onActivation) {
mid.onActivation(onActivation);
} else if (proxy) {
mid.onActivation((context: interfaces.Context, t: any) => doProxyIfNeed(metadata, t));
}
for (const item of ids) {
bind(item).toService(id);
}
}
Example #13
Source File: auto-bind.ts From malagu with MIT License | 6 votes |
export function autoBind(registry?: interfaces.ContainerModuleCallBack): interfaces.ContainerModule {
return new ContainerModule((bind, unbind, isBound, rebind) => {
const metadatas: ComponentMetadata[] = Reflect.getMetadata(METADATA_KEY.component, Reflect) || [];
for (let index = metadatas.length - 1; index >= 0; index--) {
const metadata = metadatas[index];
resolve(metadata, bind, rebind);
}
Reflect.defineMetadata(METADATA_KEY.component, [], Reflect);
const constantMetadata: ConstantOption[] = Reflect.getMetadata(METADATA_KEY.constantValue, Reflect) || [];
constantMetadata.map(metadata => resolveConstant(metadata, bind, rebind));
Reflect.defineMetadata(METADATA_KEY.constantValue, [], Reflect);
if (registry) {
registry(bind, unbind, isBound, rebind);
}
});
}
Example #14
Source File: aop-proxy-factory.ts From malagu with MIT License | 6 votes |
protected getAdvices<T>(id: interfaces.ServiceIdentifier<T>, tagValues: string[]) {
const container = ContainerProvider.provide();
const advices: T[] = [];
for (const tagValue of tagValues) {
if (container.isBoundTagged(id, AOP_TAG, tagValue)) {
advices.push(...container.getAllTagged<T>(id, AOP_TAG, tagValue));
}
}
return advices;
}
Example #15
Source File: inversify.config.ts From GWebGPUEngine with MIT License | 6 votes |
lazyMultiInject = (
serviceIdentifier: interfaces.ServiceIdentifier<any>,
) => {
const original = DECORATORS.lazyMultiInject(serviceIdentifier);
// the 'descriptor' parameter is actually always defined for class fields for Babel, but is considered undefined for TSC
// so we just hack it with ?/! combination to avoid "TS1240: Unable to resolve signature of property decorator when called as an expression"
return function(
this: any,
proto: any,
key: string,
descriptor?: IBabelPropertyDescriptor,
): void {
// make it work as usual
original.call(this, proto, key);
if (descriptor) {
// return link to proto, so own value wont be 'undefined' after component's creation
descriptor!.initializer = () => {
return proto[key];
};
}
};
}
Example #16
Source File: diContext.tsx From mo360-ftk with MIT License | 5 votes |
diContext: React.Context<interfaces.Container> = createContext(null)
Example #17
Source File: react-component.ts From malagu with MIT License | 5 votes |
ReactComponent =
function (id?: interfaces.ServiceIdentifier<any> | interfaces.ServiceIdentifier<any>[], component?: React.ComponentType<any>, rebind: boolean = false): ClassDecorator {
return (t: any) => {
Constant(id || t, component || t, rebind)(t);
};
}
Example #18
Source File: createContainer.ts From reactant with MIT License | 5 votes |
public getConstructorMetadata(
constructorFunc: Function
): interfaces.ConstructorMetadata {
const constructorMetadata = super.getConstructorMetadata(constructorFunc);
// TODO: hook
return constructorMetadata;
}
Example #19
Source File: createContainer.ts From reactant with MIT License | 5 votes |
export function bindModules(container: Container, modules: ModuleOptions[]) {
const provideMeta = getMetadata(METADATA_KEY.provide);
for (const module of modules) {
if (typeof module === 'function') {
// auto decorate `@injectable` for module.
if (!provideMeta.has(module)) decorate(injectable(), module);
autoDecorateParams(module);
container.bind(module).toSelf();
} else if (typeof module === 'object') {
if (isClassProvider(module)) {
// auto decorate `@injectable` for module.useClass
if (!provideMeta.has(module.useClass))
decorate(injectable(), module.useClass);
autoDecorateParams(module.useClass);
container.bind(module.provide).to(module.useClass);
} else if (Object.hasOwnProperty.call(module, 'useValue')) {
container
.bind(module.provide)
.toConstantValue((module as ValueProvider).useValue);
} else if (isFactoryProvider(module)) {
container
.bind(module.provide)
.toFactory((context: interfaces.Context) => {
const deps = module.deps || [];
const depInstances = deps.map((identifier) => {
// TODO: refactor with `is` assertion
const provide =
(identifier as DependencyProviderOption).provide ||
(identifier as ServiceIdentifier<any>);
if (
(identifier as DependencyProviderOption).optional &&
!context.container.isBound(
(identifier as DependencyProviderOption).provide
)
) {
return undefined;
}
return context.container.get(provide);
});
return module.useFactory(...depInstances);
});
} else if (typeof module.provide === 'function') {
// auto decorate `@injectable` for module.provide
if (!provideMeta.has(module.provide))
decorate(injectable(), module.provide);
autoDecorateParams(module.provide);
container.bind(module.provide).toSelf();
} else {
throw new Error(`${module} option error`);
}
} else {
throw new Error(`${module} option error`);
}
}
// load modules with `@injectable` decoration, but without `@optional` decoration.
container.load(autoBindModules());
}
Example #20
Source File: inversify.config.ts From GWebGPUEngine with MIT License | 5 votes |
lazyInject = (
serviceIdentifier: interfaces.ServiceIdentifier<any>,
) => {
const original = DECORATORS.lazyInject(serviceIdentifier);
// the 'descriptor' parameter is actually always defined for class fields for Babel, but is considered undefined for TSC
// so we just hack it with ?/! combination to avoid "TS1240: Unable to resolve signature of property decorator when called as an expression"
return function(
this: any,
proto: any,
key: string,
descriptor?: IBabelPropertyDescriptor,
): void {
// make it work as usual
original.call(this, proto, key);
// return link to proto, so own value wont be 'undefined' after component's creation
if (descriptor) {
descriptor.initializer = () => {
return proto[key];
};
}
};
}
Example #21
Source File: inversify.config.ts From GWebGPUEngine with MIT License | 4 votes |
// https://github.com/inversify/InversifyJS/blob/master/wiki/hierarchical_di.md#support-for-hierarchical-di-systems
export function createWorldContainer() {
const worldContainer = new Container();
worldContainer.parent = container;
/**
* bind systems
*/
worldContainer
.bind<ISystem>(IDENTIFIER.Systems)
.to(SceneGraphSystem)
.inSingletonScope()
.whenTargetNamed(IDENTIFIER.SceneGraphSystem);
worldContainer
.bind<ISystem>(IDENTIFIER.Systems)
.to(FrameGraphSystem)
.inSingletonScope()
.whenTargetNamed(IDENTIFIER.FrameGraphSystem);
worldContainer
.bind<ISystem>(IDENTIFIER.Systems)
.to(MeshSystem)
.inSingletonScope()
.whenTargetNamed(IDENTIFIER.MeshSystem);
worldContainer
.bind<ISystem>(IDENTIFIER.Systems)
.to(GeometrySystem)
.inSingletonScope()
.whenTargetNamed(IDENTIFIER.GeometrySystem);
worldContainer
.bind<ISystem>(IDENTIFIER.Systems)
.to(MaterialSystem)
.inSingletonScope()
.whenTargetNamed(IDENTIFIER.MaterialSystem);
worldContainer
.bind<ISystem>(IDENTIFIER.Systems)
.to(RendererSystem)
.inSingletonScope()
.whenTargetNamed(IDENTIFIER.RendererSystem);
// 资源池
worldContainer
.bind(IDENTIFIER.ResourcePool)
.to(ResourcePool)
.inSingletonScope();
worldContainer
.bind(IDENTIFIER.ConfigService)
.to(ConfigService)
.inSingletonScope();
worldContainer
.bind(IDENTIFIER.InteractorService)
.to(InteractorService)
.inSingletonScope();
/**
* bind render passes
*/
worldContainer
.bind<IRenderPass<any>>(IDENTIFIER.RenderPass)
.to(RenderPass)
.inSingletonScope()
.whenTargetNamed(RenderPass.IDENTIFIER);
worldContainer
.bind<IRenderPass<any>>(IDENTIFIER.RenderPass)
.to(CopyPass)
.inSingletonScope()
.whenTargetNamed(CopyPass.IDENTIFIER);
worldContainer
.bind<IRenderPass<any>>(IDENTIFIER.RenderPass)
.to(PixelPickingPass)
.inSingletonScope()
.whenTargetNamed(PixelPickingPass.IDENTIFIER);
worldContainer
.bind<interfaces.Factory<IRenderPass<any>>>(IDENTIFIER.RenderPassFactory)
.toFactory<IRenderPass<any>>((context: interfaces.Context) => {
return (name: string) => {
return context.container.getNamed(IDENTIFIER.RenderPass, name);
};
});
return worldContainer;
}