dipend
Version:
This library implements a dependency injection (DI) system in JavaScript/TypeScript, making it easier to manage dependencies in modular applications.
61 lines (59 loc) • 2.73 kB
JavaScript
/*
* Copyright 2025 Saulo V. Alvarenga. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DependencyResolver = void 0;
const enums_1 = require("../enums");
const exceptions_1 = require("../exceptions");
const strategies_1 = require("./strategies");
class DependencyResolver {
dependencyStore;
strategies = new Map();
constructor(dependencyStore) {
this.dependencyStore = dependencyStore;
}
setDefaultResolveLifecycleStrategies() {
this.strategies.set(enums_1.LifecycleEnum.SINGLETON, new strategies_1.ResolveSingletonLifecycleStrategy());
this.strategies.set(enums_1.LifecycleEnum.TRANSIENT, new strategies_1.ResolveTransientLifecycleStrategy());
}
addResolveLifecycleStrategy(lifecycle, strategy) {
this.strategies.set(lifecycle, strategy);
}
useLifecycleStrategy(dependencyRegistry, resolvedClassConstructorDependencies) {
const strategy = this.strategies.get(dependencyRegistry.lifecycle);
if (strategy === undefined) {
throw new exceptions_1.InvalidLifecycleException([dependencyRegistry.dependencyId], dependencyRegistry.lifecycle);
}
return strategy.execute({
dependencyRegistry,
resolvedClassConstructorDependencies,
});
}
resolvedInstance(dependencyRegistry) {
return dependencyRegistry.implementationDetails.instance;
}
resolve(dependencyId) {
const dependencyRegistry = this.dependencyStore.getDependency(dependencyId);
const resolvedInstance = this.resolvedInstance(dependencyRegistry);
if (resolvedInstance !== undefined) {
return resolvedInstance;
}
const classConstructorDependenciesIds = dependencyRegistry.implementationDetails.classConstructorDependenciesIds;
const resolvedClassConstructorDependencies = classConstructorDependenciesIds.map((constructorDependencyId) => this.resolve(constructorDependencyId));
return this.useLifecycleStrategy(dependencyRegistry, resolvedClassConstructorDependencies);
}
}
exports.DependencyResolver = DependencyResolver;