@jems/di
Version:
An implementation of IoC pattern based on dependency injection that allows you to granulate and decouple your libraries or applications. Wrote using SOLID principles and a variety OOP patterns implementations.
327 lines (326 loc) • 16.3 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var Errors = require("./errors/index");
var kernelConfiguration_1 = require("./kernelConfiguration");
var relationSyntax_1 = require("./fluent-syntaxes/relationSyntax");
var instanceServicingStrategy_1 = require("./servicing-strategies/instanceServicingStrategy");
var perCallDeliveryStrategy_1 = require("./delivery-strategies/perCallDeliveryStrategy");
var buildInContainerizedKernel_1 = require("./buildInContainerizedKernel");
var buildInContainer_1 = require("./buildInContainer");
/**
* Represents a kernel that manage the type registration, instance activation and servicing strategies.
* @private
*/
var BuildInKernel = /** @class */ (function () {
/**
* Instance a new kernel.
*/
function BuildInKernel() {
this._defaultContainerAlias = 'default';
this._containers = {};
var defaultContainer = this.createNewContainer(this._defaultContainerAlias, []);
this._currentContainer = defaultContainer;
this._containers[defaultContainer.getName()] = defaultContainer;
this._aliasMetadataMap = {};
this._kernelConfiguration = new kernelConfiguration_1.KernelConfiguration();
this._kernelConfiguration.defaultServicingStrategy = new instanceServicingStrategy_1.InstanceServicingStrategy();
this._kernelConfiguration.defaultDeliveryStrategy = new perCallDeliveryStrategy_1.PerCallDeliveryStrategy();
}
Object.defineProperty(BuildInKernel.prototype, "configuration", {
/**
* Returns the configuration of the kernel.
*/
get: function () {
return this._kernelConfiguration;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BuildInKernel.prototype, "aliasMetadataMap", {
/**
* Get the alias metadata map to configure aliases behavior.
*/
get: function () {
return this._aliasMetadataMap;
},
enumerable: true,
configurable: true
});
/**
* Load thegiven modules into the kernel.
* @param {Module[]} modules Represents the modules that will be loaded in the kernel.
*/
BuildInKernel.prototype.loadModules = function (modules) {
modules.forEach(function (module) {
module.initialize(this);
}.bind(this));
};
/**
* Load the given modules into the kernel asynchronous.
* @param {Module[]} modules Represents the modules that will be loaded in the kernel.
* @returns {Promise<void>} A Promise that load the modules.
*/
BuildInKernel.prototype.loadModulesAsync = function (modules) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
this.loadModules(modules);
return [2 /*return*/];
});
});
};
/**
* Return a containerized resolution syntax that allow perform resolution with an exiting container.
* @param alias Represents the alias of the container to look for.
* @return {ContainerizedKernel} The containerized resolution systax.
*/
BuildInKernel.prototype.usingContainer = function (alias) {
if (!this.hasContainer(alias)) {
throw new Errors.UnregisteredAliasError('There is not any container with the given alias.');
}
return this.getContainerizedKernel(this._containers[alias]);
};
/**
* Return a containerized resolution syntax that allow perform resolution with the defautl container.
* @return {ContainerizedKernel} The containerized resolution systax.
*/
BuildInKernel.prototype.usingDefaultContainer = function () {
return this.getContainerizedKernel(this._currentContainer);
};
/**
* Creates and returns a container with the given alias.
* @param {string} alias Represents the alias of the container.
* @param {string[]} supports Represents the aliases of the supports containers.
* @return {Container} The created container.
*/
BuildInKernel.prototype.createContainer = function (alias, supports) {
this.createNewContainer(alias, supports);
};
/**
* Returns a boolean value specifying if the given alias can be resolved.
* @param {string} alias Represents the alias to look for.
* @return {boolean} True if the given alias can be resolved.
*/
BuildInKernel.prototype.canResolve = function (alias) {
return this._currentContainer.canResolve(alias);
};
/**
* Return an resolved instance using the given reference that could be a class, function or alias.
* @param {{ new ():any } | Function | string} reference Represents the reference that must be resolved, it could be a class, function or alias.
* @param {ResolutionOption} resolutionOption Represents the options to resolve the the reference.
* @return {any} The resolved object.
*/
BuildInKernel.prototype.resolve = function (reference, resolutionOption) {
return this.usingDefaultContainer().resolve(reference, resolutionOption);
};
/**
* Return a promise that provided a resolved instance using the given reference that could be a class, function or alias.
* @param {{ new ():any } | Function | string} reference Represents the reference that must be resolved, it could be a class, function or alias.
* @param {ResolutionOption} resolutionOption Represents the options to resolve the the reference.
* @return {Promise<any>} A promise that resolve the objects.
*/
BuildInKernel.prototype.resolveAsync = function (reference, resolutionOption) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.resolveAsync(reference, resolutionOption)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Return an resolved instance using the given reference that could be a class, function or alias.
* @param {{ new ():any } | Function | string} reference Represents the reference that must be resolved, it could be a class, function or alias.
* @param {ResolutionContext} resolutionContext Represents the context of the resolution.
* @return {any} The resolved object.
*/
BuildInKernel.prototype.resolveWithContext = function (reference, resolutionContext) {
return this.usingDefaultContainer().resolveWithContext(reference, resolutionContext);
};
/**
* Return a promise that provided a resolved instance using the given reference that could be a class, function or alias.
* @param {{ new ():any } | Function | string} reference Represents the reference that must be resolved, it could be a class, function or alias.
* @param {ResolutionContext} resolutionContext Represents the context of the resolution.
* @return {Promise<any>} A promise that resolve the objects.
*/
BuildInKernel.prototype.resolveWithContextAsync = function (reference, resolutionContext) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.usingDefaultContainer().resolveWithContextAsync(reference, resolutionContext)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Return an alias bind fluent syntax that allow register dependencies metadata in a fluent api syntax.
* @param {string} alias Represents the alias to look for.
* @returns {ToSyntax} A fluent bind.
*/
BuildInKernel.prototype.bind = function (alias) {
return new relationSyntax_1.RelationSyntax(this).bind(alias);
};
/**
* Unbind all dependencies metadata with the given alias from the container.
* @param {string} alias Represents the alias to look for.
*/
BuildInKernel.prototype.unbindWithAlias = function (alias) {
this.unregisterDependenciesMetadataWithAlias(alias);
};
/**
* Unbind the dependency metadata with the given identifier from the container.
* @param {string} identifier Represents the identifier to look for.
*/
BuildInKernel.prototype.unbindWithIdentifier = function (identifier) {
this.unregisterDependencyMetadataWithIdentifier(identifier);
};
/**
* Returns the registered dependency metadata with the given alias and identifier.
* @param {string} identifier Represents the identifier to look for.
* @returns {string} Return dependency metadata with the given identifier.
*/
BuildInKernel.prototype.getDependencyMetadataWithIdentifier = function (identifier) {
return this.usingDefaultContainer().getDependencyMetadataWithIdentifier(identifier);
};
/**
* Returns the generated identifier and register the given metadata with the given alias for his future activation.
* @param {string} alias Represents the alias.
* @param {DependencyMetadata} dependencyMetadata Represents the dependency metadata.
* @returns {string} Returns the dependency metadata generated identifier.
*/
BuildInKernel.prototype.registerDependencyMetadata = function (alias, dependencyMetadata) {
return this.usingDefaultContainer().registerDependencyMetadata(alias, dependencyMetadata);
};
/**
* Unregister all registered dependencies metadata with the given alias.
* @param {string} alias Represents the alias to to look for.
*/
BuildInKernel.prototype.unregisterDependenciesMetadataWithAlias = function (alias) {
this.usingDefaultContainer().unregisterDependenciesMetadataWithAlias(alias);
};
/**
* Unregister the dependency metadata with the given alias and identifier.
* @param {string} identifier Represents the identifier to look for.
*/
BuildInKernel.prototype.unregisterDependencyMetadataWithIdentifier = function (identifier) {
this.usingDefaultContainer().unregisterDependencyMetadataWithIdentifier(identifier);
};
/**
* Removes the container with the given alias.
* @param {string} alias Represents the alias of the container.
*/
BuildInKernel.prototype.removeContainer = function (alias) {
if (this.hasContainer(alias)) {
delete this._containers[alias];
}
else {
throw new Errors.InvalidDataError("The given container alias [" + alias + "] is not registered.");
}
};
/**
* Returns a boolean value specifying if the kernel has a container with the given alias.
* @param {string} alias Represents the alias of the container.
* @returns {boolean} True if the kernel has the container.
*/
BuildInKernel.prototype.hasContainer = function (alias) {
return !(!this._containers[alias]);
};
/**
* Dispose and release all the objects and containers in the kernel.
*/
BuildInKernel.prototype.dispose = function () {
for (var containerAlias in this._containers) {
if (this._containers.hasOwnProperty(containerAlias)) {
this._containers[containerAlias].dispose();
delete this._containers[containerAlias];
}
}
};
/**
* Dispose and release all the objects and containers in the kernel asynchronous.
* @returns {Promise<void>} A promise that dispose the kernel.
*/
BuildInKernel.prototype.disposeAsync = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
this.dispose();
return [2 /*return*/];
});
});
};
BuildInKernel.prototype.createNewContainer = function (alias, supports) {
if (!(this.hasContainer(alias))) {
if (supports && supports.length > 0) {
this.validateCiclycDependency([alias], supports);
}
this._containers[alias] = new buildInContainer_1.BuildInContainer(this, alias);
if (supports && supports.length > 0) {
this._containers[alias].setSupportContainersAliases(supports);
}
return this._containers[alias];
}
else {
throw new Errors.InvalidDataError("The given container alias [" + alias + "] is already registered");
}
};
BuildInKernel.prototype.getContainerizedKernel = function (container) {
return new buildInContainerizedKernel_1.BuildInContainerizedKernel(container);
};
BuildInKernel.prototype.validateCiclycDependency = function (stack, supports) {
if (!supports) {
return;
}
for (var supportAliasIndex = 0; supportAliasIndex < supports.length; supportAliasIndex++) {
for (var stackAliasIndex = 0; stackAliasIndex < stack.length; stackAliasIndex++) {
var supportAlias = supports[supportAliasIndex];
if (supportAlias === stack[stackAliasIndex]) {
throw new Errors.CyclicDependencyError('An cyclic dependency has been found for containers in the addition of support.', stack);
}
if (!this.hasContainer(supportAlias)) {
throw new Errors.InvalidDataError("The given support container alias [" + supportAlias + "] is not registered");
}
stack.push(supportAlias);
this.validateCiclycDependency(stack, this._containers[supportAlias].getSupportContainersAliases());
stack.splice(stack.length - 1, 1);
}
}
};
return BuildInKernel;
}());
exports.BuildInKernel = BuildInKernel;