@electron-tools/ioc
Advanced tools
Comparing version 1.0.8 to 1.0.9
@@ -1,236 +0,11 @@ | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
// src/index.ts | ||
var src_exports = {}; | ||
__export(src_exports, { | ||
INSTANTIATION_SERVICE_ID: () => INSTANTIATION_SERVICE_ID, | ||
default: () => InstantiationService, | ||
inject: () => inject, | ||
register: () => register, | ||
service: () => service | ||
}); | ||
module.exports = __toCommonJS(src_exports); | ||
// src/instantiation.ts | ||
var import_reflect_metadata = require("reflect-metadata"); | ||
// src/graph.ts | ||
var Node = class { | ||
constructor(data) { | ||
this.incoming = /* @__PURE__ */ new Map(); | ||
this.outgoing = /* @__PURE__ */ new Map(); | ||
this.data = data; | ||
} | ||
}; | ||
var Graph = class { | ||
constructor(_hashFn) { | ||
this._hashFn = _hashFn; | ||
this._nodes = /* @__PURE__ */ new Map(); | ||
} | ||
roots() { | ||
const ret = []; | ||
for (const node of this._nodes.values()) { | ||
if (node.outgoing.size === 0) { | ||
ret.push(node); | ||
} | ||
} | ||
return ret; | ||
} | ||
insertEdge(from, to) { | ||
const fromNode = this.lookupOrInsertNode(from); | ||
const toNode = this.lookupOrInsertNode(to); | ||
fromNode.outgoing.set(this._hashFn(to), toNode); | ||
toNode.incoming.set(this._hashFn(from), fromNode); | ||
} | ||
removeNode(data) { | ||
const key = this._hashFn(data); | ||
this._nodes.delete(key); | ||
for (const node of this._nodes.values()) { | ||
node.outgoing.delete(key); | ||
node.incoming.delete(key); | ||
} | ||
} | ||
lookupOrInsertNode(data) { | ||
const key = this._hashFn(data); | ||
let node = this._nodes.get(key); | ||
if (!node) { | ||
node = new Node(data); | ||
this._nodes.set(key, node); | ||
} | ||
return node; | ||
} | ||
lookup(data) { | ||
return this._nodes.get(this._hashFn(data)); | ||
} | ||
isEmpty() { | ||
return this._nodes.size === 0; | ||
} | ||
toString() { | ||
const data = []; | ||
for (const [key, value] of this._nodes) { | ||
data.push(`${key}, (incoming)[${[...value.incoming.keys()].join(", ")}], (outgoing)[${[...value.outgoing.keys()].join(",")}]`); | ||
} | ||
return data.join("\n"); | ||
} | ||
findCycleSlow() { | ||
for (const [id, node] of this._nodes) { | ||
const seen = /* @__PURE__ */ new Set([id]); | ||
const res = this._findCycle(node, seen); | ||
if (res) { | ||
return res; | ||
} | ||
} | ||
return void 0; | ||
} | ||
_findCycle(node, seen) { | ||
for (const [id, outgoing] of node.outgoing) { | ||
if (seen.has(id)) { | ||
return [...seen, id].join(" -> "); | ||
} | ||
seen.add(id); | ||
const value = this._findCycle(outgoing, seen); | ||
if (value) { | ||
return value; | ||
} | ||
seen.delete(id); | ||
} | ||
return void 0; | ||
} | ||
}; | ||
// src/instantiation.ts | ||
var serviceCtorStore = /* @__PURE__ */ new Map(); | ||
var INSTANTIATION_SERVICE_ID = Symbol.for("instantiationService"); | ||
var InstantiationService = class { | ||
constructor() { | ||
this.serviceStore = /* @__PURE__ */ new Map(); | ||
this.serviceStore.set(INSTANTIATION_SERVICE_ID, this); | ||
} | ||
get services() { | ||
return this.serviceStore; | ||
} | ||
init() { | ||
for (const serviceId of serviceCtorStore.keys()) { | ||
this.getService(serviceId); | ||
} | ||
} | ||
registerService(id, service2) { | ||
this.serviceStore.set(id, service2); | ||
} | ||
getService(id) { | ||
if (this.serviceStore.has(id)) | ||
return this.serviceStore.get(id); | ||
return this.createAndCacheService(id); | ||
} | ||
createAndCacheService(serviceId) { | ||
const ServiceCtor = this.getServiceCtorById(serviceId); | ||
if (!ServiceCtor) | ||
throw new Error(`[InstantiationService] service ${serviceId} not found!`); | ||
const graph = new Graph((node) => node.serviceId.toString()); | ||
const stack = [{ ctor: ServiceCtor, serviceId }]; | ||
while (stack.length) { | ||
const node = stack.pop(); | ||
graph.lookupOrInsertNode(node); | ||
const dependencies = (this.getServiceDependencies(node.ctor) || []).sort((a, b) => a.parameterIndex - b.parameterIndex); | ||
for (const dependency of dependencies) { | ||
if (this.serviceStore.has(dependency.id)) | ||
continue; | ||
const ServiceCtor2 = this.getServiceCtorById(dependency.id); | ||
const dependencyNode = { ctor: ServiceCtor2, serviceId: dependency.id }; | ||
if (!graph.lookup(dependencyNode)) { | ||
stack.push(dependencyNode); | ||
} | ||
graph.insertEdge(node, dependencyNode); | ||
} | ||
} | ||
while (true) { | ||
const roots = graph.roots(); | ||
if (roots.length === 0) { | ||
if (!graph.isEmpty()) { | ||
throw new CyclicDependencyError(graph); | ||
} | ||
break; | ||
} | ||
for (const root of roots) { | ||
const { ctor: ServiceCtor2, serviceId: serviceId2 } = root.data; | ||
const dependencies = this.getServiceDependencies(ServiceCtor2) || []; | ||
const args = dependencies.map(({ id }) => this.getService(id)); | ||
const service2 = new ServiceCtor2(...args); | ||
this.serviceStore.set(serviceId2, service2); | ||
graph.removeNode(root.data); | ||
} | ||
} | ||
return this.getService(serviceId); | ||
} | ||
getServiceDependencies(Ctor) { | ||
return Reflect.getOwnMetadata(dependencyMetadataKey, Ctor); | ||
} | ||
getServiceCtorById(id) { | ||
if (!serviceCtorStore.has(id)) { | ||
throw new Error(`service ${id} not found!`); | ||
} | ||
return serviceCtorStore.get(id); | ||
} | ||
}; | ||
var CyclicDependencyError = class extends Error { | ||
constructor(graph) { | ||
var _a; | ||
super("cyclic dependency between services"); | ||
this.message = (_a = graph.findCycleSlow()) != null ? _a : `UNABLE to detect cycle, dumping graph: | ||
${graph.toString()}`; | ||
} | ||
}; | ||
var dependencyMetadataKey = Symbol.for("$di$dependency"); | ||
function register(id, Ctor) { | ||
if (serviceCtorStore.has(id)) | ||
throw new Error(`service ${id} already exist, do not register again`); | ||
serviceCtorStore.set(id, Ctor); | ||
} | ||
function service(id) { | ||
return (Ctor) => { | ||
const serviceId = id || Ctor.name.slice(0, 1).toLowerCase().concat(Ctor.name.slice(1)); | ||
if (serviceCtorStore.has(serviceId)) | ||
throw new Error(`service ${serviceId} already exist, do not register again`); | ||
serviceCtorStore.set(serviceId, Ctor); | ||
}; | ||
} | ||
function inject(id) { | ||
return (Ctor, parameterKey, parameterIndex) => { | ||
if (Reflect.hasOwnMetadata(dependencyMetadataKey, Ctor)) { | ||
const dependencies = Reflect.getOwnMetadata(dependencyMetadataKey, Ctor); | ||
Reflect.defineMetadata(dependencyMetadataKey, [ | ||
...dependencies, | ||
{ | ||
id, | ||
parameterKey, | ||
parameterIndex | ||
} | ||
], Ctor); | ||
} else { | ||
Reflect.defineMetadata(dependencyMetadataKey, [ | ||
{ | ||
id, | ||
parameterKey, | ||
parameterIndex | ||
} | ||
], Ctor); | ||
} | ||
}; | ||
} | ||
//# sourceMappingURL=index.js.map | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.INSTANTIATION_SERVICE_ID = exports.register = exports.inject = exports.service = exports.default = void 0; | ||
var instantiation_1 = require("./instantiation"); | ||
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return __importDefault(instantiation_1).default; } }); | ||
var instantiation_2 = require("./instantiation"); | ||
Object.defineProperty(exports, "service", { enumerable: true, get: function () { return instantiation_2.service; } }); | ||
Object.defineProperty(exports, "inject", { enumerable: true, get: function () { return instantiation_2.inject; } }); | ||
Object.defineProperty(exports, "register", { enumerable: true, get: function () { return instantiation_2.register; } }); | ||
Object.defineProperty(exports, "INSTANTIATION_SERVICE_ID", { enumerable: true, get: function () { return instantiation_2.INSTANTIATION_SERVICE_ID; } }); | ||
//# sourceMappingURL=index.js.map |
@@ -1,214 +0,3 @@ | ||
// src/instantiation.ts | ||
import "reflect-metadata"; | ||
// src/graph.ts | ||
var Node = class { | ||
constructor(data) { | ||
this.incoming = /* @__PURE__ */ new Map(); | ||
this.outgoing = /* @__PURE__ */ new Map(); | ||
this.data = data; | ||
} | ||
}; | ||
var Graph = class { | ||
constructor(_hashFn) { | ||
this._hashFn = _hashFn; | ||
this._nodes = /* @__PURE__ */ new Map(); | ||
} | ||
roots() { | ||
const ret = []; | ||
for (const node of this._nodes.values()) { | ||
if (node.outgoing.size === 0) { | ||
ret.push(node); | ||
} | ||
} | ||
return ret; | ||
} | ||
insertEdge(from, to) { | ||
const fromNode = this.lookupOrInsertNode(from); | ||
const toNode = this.lookupOrInsertNode(to); | ||
fromNode.outgoing.set(this._hashFn(to), toNode); | ||
toNode.incoming.set(this._hashFn(from), fromNode); | ||
} | ||
removeNode(data) { | ||
const key = this._hashFn(data); | ||
this._nodes.delete(key); | ||
for (const node of this._nodes.values()) { | ||
node.outgoing.delete(key); | ||
node.incoming.delete(key); | ||
} | ||
} | ||
lookupOrInsertNode(data) { | ||
const key = this._hashFn(data); | ||
let node = this._nodes.get(key); | ||
if (!node) { | ||
node = new Node(data); | ||
this._nodes.set(key, node); | ||
} | ||
return node; | ||
} | ||
lookup(data) { | ||
return this._nodes.get(this._hashFn(data)); | ||
} | ||
isEmpty() { | ||
return this._nodes.size === 0; | ||
} | ||
toString() { | ||
const data = []; | ||
for (const [key, value] of this._nodes) { | ||
data.push(`${key}, (incoming)[${[...value.incoming.keys()].join(", ")}], (outgoing)[${[...value.outgoing.keys()].join(",")}]`); | ||
} | ||
return data.join("\n"); | ||
} | ||
findCycleSlow() { | ||
for (const [id, node] of this._nodes) { | ||
const seen = /* @__PURE__ */ new Set([id]); | ||
const res = this._findCycle(node, seen); | ||
if (res) { | ||
return res; | ||
} | ||
} | ||
return void 0; | ||
} | ||
_findCycle(node, seen) { | ||
for (const [id, outgoing] of node.outgoing) { | ||
if (seen.has(id)) { | ||
return [...seen, id].join(" -> "); | ||
} | ||
seen.add(id); | ||
const value = this._findCycle(outgoing, seen); | ||
if (value) { | ||
return value; | ||
} | ||
seen.delete(id); | ||
} | ||
return void 0; | ||
} | ||
}; | ||
// src/instantiation.ts | ||
var serviceCtorStore = /* @__PURE__ */ new Map(); | ||
var INSTANTIATION_SERVICE_ID = Symbol.for("instantiationService"); | ||
var InstantiationService = class { | ||
constructor() { | ||
this.serviceStore = /* @__PURE__ */ new Map(); | ||
this.serviceStore.set(INSTANTIATION_SERVICE_ID, this); | ||
} | ||
get services() { | ||
return this.serviceStore; | ||
} | ||
init() { | ||
for (const serviceId of serviceCtorStore.keys()) { | ||
this.getService(serviceId); | ||
} | ||
} | ||
registerService(id, service2) { | ||
this.serviceStore.set(id, service2); | ||
} | ||
getService(id) { | ||
if (this.serviceStore.has(id)) | ||
return this.serviceStore.get(id); | ||
return this.createAndCacheService(id); | ||
} | ||
createAndCacheService(serviceId) { | ||
const ServiceCtor = this.getServiceCtorById(serviceId); | ||
if (!ServiceCtor) | ||
throw new Error(`[InstantiationService] service ${serviceId} not found!`); | ||
const graph = new Graph((node) => node.serviceId.toString()); | ||
const stack = [{ ctor: ServiceCtor, serviceId }]; | ||
while (stack.length) { | ||
const node = stack.pop(); | ||
graph.lookupOrInsertNode(node); | ||
const dependencies = (this.getServiceDependencies(node.ctor) || []).sort((a, b) => a.parameterIndex - b.parameterIndex); | ||
for (const dependency of dependencies) { | ||
if (this.serviceStore.has(dependency.id)) | ||
continue; | ||
const ServiceCtor2 = this.getServiceCtorById(dependency.id); | ||
const dependencyNode = { ctor: ServiceCtor2, serviceId: dependency.id }; | ||
if (!graph.lookup(dependencyNode)) { | ||
stack.push(dependencyNode); | ||
} | ||
graph.insertEdge(node, dependencyNode); | ||
} | ||
} | ||
while (true) { | ||
const roots = graph.roots(); | ||
if (roots.length === 0) { | ||
if (!graph.isEmpty()) { | ||
throw new CyclicDependencyError(graph); | ||
} | ||
break; | ||
} | ||
for (const root of roots) { | ||
const { ctor: ServiceCtor2, serviceId: serviceId2 } = root.data; | ||
const dependencies = this.getServiceDependencies(ServiceCtor2) || []; | ||
const args = dependencies.map(({ id }) => this.getService(id)); | ||
const service2 = new ServiceCtor2(...args); | ||
this.serviceStore.set(serviceId2, service2); | ||
graph.removeNode(root.data); | ||
} | ||
} | ||
return this.getService(serviceId); | ||
} | ||
getServiceDependencies(Ctor) { | ||
return Reflect.getOwnMetadata(dependencyMetadataKey, Ctor); | ||
} | ||
getServiceCtorById(id) { | ||
if (!serviceCtorStore.has(id)) { | ||
throw new Error(`service ${id} not found!`); | ||
} | ||
return serviceCtorStore.get(id); | ||
} | ||
}; | ||
var CyclicDependencyError = class extends Error { | ||
constructor(graph) { | ||
var _a; | ||
super("cyclic dependency between services"); | ||
this.message = (_a = graph.findCycleSlow()) != null ? _a : `UNABLE to detect cycle, dumping graph: | ||
${graph.toString()}`; | ||
} | ||
}; | ||
var dependencyMetadataKey = Symbol.for("$di$dependency"); | ||
function register(id, Ctor) { | ||
if (serviceCtorStore.has(id)) | ||
throw new Error(`service ${id} already exist, do not register again`); | ||
serviceCtorStore.set(id, Ctor); | ||
} | ||
function service(id) { | ||
return (Ctor) => { | ||
const serviceId = id || Ctor.name.slice(0, 1).toLowerCase().concat(Ctor.name.slice(1)); | ||
if (serviceCtorStore.has(serviceId)) | ||
throw new Error(`service ${serviceId} already exist, do not register again`); | ||
serviceCtorStore.set(serviceId, Ctor); | ||
}; | ||
} | ||
function inject(id) { | ||
return (Ctor, parameterKey, parameterIndex) => { | ||
if (Reflect.hasOwnMetadata(dependencyMetadataKey, Ctor)) { | ||
const dependencies = Reflect.getOwnMetadata(dependencyMetadataKey, Ctor); | ||
Reflect.defineMetadata(dependencyMetadataKey, [ | ||
...dependencies, | ||
{ | ||
id, | ||
parameterKey, | ||
parameterIndex | ||
} | ||
], Ctor); | ||
} else { | ||
Reflect.defineMetadata(dependencyMetadataKey, [ | ||
{ | ||
id, | ||
parameterKey, | ||
parameterIndex | ||
} | ||
], Ctor); | ||
} | ||
}; | ||
} | ||
export { | ||
INSTANTIATION_SERVICE_ID, | ||
InstantiationService as default, | ||
inject, | ||
register, | ||
service | ||
}; | ||
//# sourceMappingURL=index.js.map | ||
export { default } from './instantiation'; | ||
export { service, inject, register, INSTANTIATION_SERVICE_ID } from './instantiation'; | ||
//# sourceMappingURL=index.js.map |
@@ -1,34 +0,2 @@ | ||
declare type DependenciesValue = Array<{ | ||
id: string; | ||
parameterKey: string; | ||
parameterIndex: number; | ||
}>; | ||
export declare function inject(id: ServiceUniqueId): (Ctor: ServiceCtor, parameterKey: string, parameterIndex: number) => void; | ||
export declare const INSTANTIATION_SERVICE_ID: unique symbol; | ||
declare class InstantiationService { | ||
private readonly serviceStore; | ||
get services(): Map<ServiceUniqueId, unknown>; | ||
constructor(); | ||
init(): void; | ||
registerService(id: ServiceUniqueId, service: any): void; | ||
getService<S = any>(id: ServiceUniqueId): S; | ||
createAndCacheService<S = any>(serviceId: ServiceUniqueId): S; | ||
getServiceDependencies(Ctor: ServiceCtor): DependenciesValue; | ||
getServiceCtorById(id: ServiceUniqueId): ServiceCtor; | ||
} | ||
export default InstantiationService; | ||
export declare function register(id: ServiceUniqueId, Ctor: ServiceCtor): void; | ||
export declare function service(id?: ServiceUniqueId): (Ctor: ServiceCtor) => void; | ||
declare interface ServiceCtor<T = any, A extends any[] = any[]> { | ||
new (...args: A): T; | ||
} | ||
declare type ServiceUniqueId = string | Symbol; | ||
export { } | ||
export { default } from './instantiation'; | ||
export { service, inject, register, INSTANTIATION_SERVICE_ID } from './instantiation'; |
{ | ||
"name": "@electron-tools/ioc", | ||
"version": "1.0.8", | ||
"version": "1.0.9", | ||
"description": "DI implement of IOC", | ||
"main": "dist/cjs/index.js", | ||
"module": "dist/esm/index.js", | ||
"types": "dist/types/index.d.ts", | ||
"main": "./dist/cjs/index.js", | ||
"module": "./dist/esm/index.js", | ||
"types": "./dist/types/index.d.ts", | ||
"exports": { | ||
".": { | ||
"require": "./dist/cjs/index.js", | ||
"import": "./dist/esm/index.js", | ||
"types": "./dist/types/index.d.ts", | ||
"default": "./dist/esm/index.js" | ||
}, | ||
"./*": { | ||
"require": "./dist/cjs/*.js", | ||
"import": "./dist/esm/*.js", | ||
"types": "./dist/types/*.d.ts", | ||
"default": "./dist/esm/*.js" | ||
} | ||
}, | ||
"files": [ | ||
"dist" | ||
"dist", | ||
"!dist/*.tsbuildinfo" | ||
], | ||
@@ -18,10 +33,17 @@ "author": "heychenfq <heychenfq@foxmail.com>", | ||
"devDependencies": { | ||
"eslibc": "0.0.3" | ||
"@types/jest": "^27.5.2", | ||
"@types/node": "^18.0.0", | ||
"jest": "^28.1.0", | ||
"rimraf": "^3.0.2", | ||
"ts-jest": "^28.0.2", | ||
"ts-node": "^10.8.0", | ||
"typescript": "^4.7.3" | ||
}, | ||
"scripts": { | ||
"clean": "eslibc clean", | ||
"dev": "eslibc dev", | ||
"build": "eslibc clean && eslibc build" | ||
"clean": "rimraf dist", | ||
"dev": "tsc -b -w", | ||
"build": "pnpm clean && tsc -b", | ||
"test": "jest" | ||
}, | ||
"readme": "# Introduction\n\nA simple DI implement of IOC using typescript. inspired by vscode IOC implement.\n\n# Installation\n\n```bash\n# install by npm\n$npm install @electron-tools/ioc\n# install by pnpm\n$pnpm add @electron-tools/ioc\n# install by yarn\n$yarn add @electron-tools/ioc\n```\n\n# Usage\n\n1. enable `experimentalDecorators` option in your tsconfig.json.\n\n2. register your service by `service` decorator exported from this package.\n\n```typescript\n// src/serviceA.ts\nimport { service } from '@electron-tools/ioc';\n\n@service('serviceA') // register ServiceA with unique id 'serviceA' using service decorator exported by this package.\nclass ServiceA {\n // ....\n}\n```\n\n3. use `inject` decorator inject your service to another service.\n\n```typescript\n// src/serviceB.ts\nimport { service, inject } from '@electron-tools/ioc';\n\n@service('serviceB') // also register ServiceB with unique id 'serviceB'\nclass ServiceB {\n constructor(\n @inject('serviceA') // inject serviceA to serviceB, the only args passed to inject is the service unique id.\n readonly serviceA: ServiceA,\n ) {}\n}\n```\n\n4. import all your services and crate a IOC instance in your entry file.\n\n```typescript\n// src/index.ts\nimport IOC from '@electron-tools/ioc';\nimport './serviceA.ts';\nimport './serviceB.ts';\n\nconst ioc = new IOC();\nconst serviceA = ioc.getService('serviceA');\nconst serviceB = ioc.getService('serviceB');\nconsole.log(serviceA instanceof ServiceA); // true\nconsole.log(serviceB instanceof ServiceB); // true\nconsole.log(serviceA === serviceB.a); // true\n```\n\n# Features\n\n1. Instance all service in one place. \n by default. service only be instanced when needed. in the case above. if you only call `ioc.getService('serviceA')`, serviceB will not be instance, cause serviceB is not dependencied by any service, but if you only call `ioc.getService('serviceB')`, serviceA will be instance, and inject into serviceB. this maybe not what you want. you can init all services in one place by call `ioc.init()`.\n\n```typescript\nconst ioc = new IOC();\nioc.init(); // this statement will instance all services registered.\n```\n\n2. Cycle reference.\n if there are some cycle reference between your services. such as serviceA dependencied by serviceB, serviceB also dependencied by serviceA, you can resolve this issue by get service later instead of constructor of service.\n\n```typescript\n// src/serviceA.ts\nimport IOC, { service, inject, INSTANTIATION_SERVICE_ID } from '@electron-tools/ioc';\n\n@service('serviceA') // register ServiceA with unique id 'serviceA' using service decorator exported by ioc.\nclass ServiceA {\n constructor(\n @inject(INSTANTIATION_SERVICE_ID) readonly ioc: IOC, // ioc itself is also a service can be injected.\n ) {}\n\n someMethod() {\n // dynamic get serviceB by ioc#getService API. then you can do anything what serviceB can do.\n const serviceB = this.ioc.getService('serviceB');\n serviceB.xxx;\n }\n}\n```\n" | ||
"readme": "# @electron-tools/ioc\n\n## Introduction\n\nA simple DI implement of IOC using typescript. inspired by vscode IOC implement.\n\n## Installation\n\n```bash\n# install by npm\n$npm install @electron-tools/ioc\n# install by pnpm\n$pnpm add @electron-tools/ioc\n# install by yarn\n$yarn add @electron-tools/ioc\n```\n\n## Usage\n\n1. enable `experimentalDecorators` option in your tsconfig.json.\n\n2. register your service by `service` decorator exported from this package.\n\n```ts\n// src/serviceA.ts\nimport { service } from '@electron-tools/ioc';\n\n@service('serviceA') // register ServiceA with unique id 'serviceA' using service decorator exported by this package.\nclass ServiceA {\n // ....\n}\n```\n\n3. use `inject` decorator inject your service to another service.\n\n```ts\n// src/serviceB.ts\nimport { service, inject } from '@electron-tools/ioc';\n\n@service('serviceB') // also register ServiceB with unique id 'serviceB'\nclass ServiceB {\n constructor(\n @inject('serviceA') // inject serviceA to serviceB, the only args passed to inject is the service unique id.\n readonly serviceA: ServiceA,\n ) {}\n}\n```\n\n4. import all your services and crate a IOC instance in your entry file.\n\n```ts\n// src/index.ts\nimport IOC from '@electron-tools/ioc';\nimport './serviceA.ts';\nimport './serviceB.ts';\n\nconst ioc = new IOC();\nconst serviceA = ioc.getService('serviceA');\nconst serviceB = ioc.getService('serviceB');\nconsole.log(serviceA instanceof ServiceA); // true\nconsole.log(serviceB instanceof ServiceB); // true\nconsole.log(serviceA === serviceB.a); // true\n```\n\n## Features\n\n1. Instance all service in one place. \n by default. service only be instanced when needed. in the case above. if you only call `ioc.getService('serviceA')`, serviceB will not be instance, cause serviceB is not dependencied by any service, but if you only call `ioc.getService('serviceB')`, serviceA will be instance, and inject into serviceB. this maybe not what you want. you can init all services in one place by call `ioc.init()`.\n\n```ts\nconst ioc = new IOC();\nioc.init(); // this statement will instance all services registered.\n```\n\n2. Cycle reference.\n if there are some cycle reference between your services. such as serviceA dependencied by serviceB, serviceB also dependencied by serviceA, you can resolve this issue by get service later instead of constructor of service.\n\n```ts\n// src/serviceA.ts\nimport IOC, { service, inject, INSTANTIATION_SERVICE_ID } from '@electron-tools/ioc';\n\n@service('serviceA') // register ServiceA with unique id 'serviceA' using service decorator exported by ioc.\nclass ServiceA {\n constructor(\n @inject(INSTANTIATION_SERVICE_ID) readonly ioc: IOC, // ioc itself is also a service can be injected.\n ) {}\n\n someMethod() {\n // dynamic get serviceB by ioc#getService API. then you can do anything what serviceB can do.\n const serviceB = this.ioc.getService('serviceB');\n serviceB.xxx;\n }\n}\n```\n" | ||
} |
@@ -1,6 +0,8 @@ | ||
# Introduction | ||
# @electron-tools/ioc | ||
## Introduction | ||
A simple DI implement of IOC using typescript. inspired by vscode IOC implement. | ||
# Installation | ||
## Installation | ||
@@ -16,3 +18,3 @@ ```bash | ||
# Usage | ||
## Usage | ||
@@ -23,3 +25,3 @@ 1. enable `experimentalDecorators` option in your tsconfig.json. | ||
```typescript | ||
```ts | ||
// src/serviceA.ts | ||
@@ -36,3 +38,3 @@ import { service } from '@electron-tools/ioc'; | ||
```typescript | ||
```ts | ||
// src/serviceB.ts | ||
@@ -52,3 +54,3 @@ import { service, inject } from '@electron-tools/ioc'; | ||
```typescript | ||
```ts | ||
// src/index.ts | ||
@@ -67,3 +69,3 @@ import IOC from '@electron-tools/ioc'; | ||
# Features | ||
## Features | ||
@@ -73,3 +75,3 @@ 1. Instance all service in one place. | ||
```typescript | ||
```ts | ||
const ioc = new IOC(); | ||
@@ -82,3 +84,3 @@ ioc.init(); // this statement will instance all services registered. | ||
```typescript | ||
```ts | ||
// src/serviceA.ts | ||
@@ -85,0 +87,0 @@ import IOC, { service, inject, INSTANTIATION_SERVICE_ID } from '@electron-tools/ioc'; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
18
503
95
41569
7
1