Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

inversify

Package Overview
Dependencies
Maintainers
1
Versions
88
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

inversify - npm Package Compare versions

Comparing version 2.0.0-alpha.0 to 2.0.0-alpha.1

src/bindings/binding_type.js

2

package.json
{
"name": "inversify",
"version": "2.0.0-alpha.0",
"version": "2.0.0-alpha.1",
"description": "A lightweight IoC container written in TypeScript.",

@@ -5,0 +5,0 @@ "main": "dist/inversify.js",

@@ -47,54 +47,62 @@ # InversifyJS

# The Basics (with TypeScript)
The main goal of InversifyJS is top allow JavaScript developers to write code that adheres to the SOLID principles. Many of these principles refer to the usage of interfaces. The main reason why it is not possible to write native SOLID JavaScript is because the language lacks interfaces. In the other hand, TypeScript features interfaces, so, if you are going to use InversifyJS it is recommended to work with TypeScript to get the most out of it.
The main goal of InversifyJS is top allow JavaScript developers to write code that adheres to the SOLID principles.
Many of these principles refer to the usage of interfaces.
The main reason why it is not possible to write native SOLID JavaScript is because the language lacks interfaces.
In the other hand, TypeScript features interfaces, so, if you are going to use InversifyJS it is recommended
to work with TypeScript to get the most out of it.
#### 1. Declare interfaces & implementations
Our goal is to write SOLID code. This means that we should "depend upon Abstractions. Do not depend upon concretions." so we will start by declaring some interfaces (abstractions).
Our goal is to write SOLID code. This means that we should "depend upon Abstractions. Do not depend upon concretions."
so we will start by declaring some interfaces (abstractions).
```
interface FooInterface {
log() : void;
interface INinja {
fight(): string;
sneak(): string;
}
interface BarInterface {
log() : void;
interface IKatana {
hit(): string;
}
interface FooBarInterface {
log() : void;
interface IShuriken {
throw();
}
```
We can continue declaring some classes which implement them (concretions). We will start by declaring two classes (Foo & Bar) which don't have any dependencies.
We can continue declaring some classes which implement them (concretions).
We will start by declaring two classes (`Katana` & `Shuriken`) which don't have any dependencies.
```
class Foo implements FooInterface {
public log(){
console.log("foo");
}
class Katana implements IKatana {
public hit() {
return "cut!";
}
}
class Bar implements BarInterface {
public log(){
console.log("bar");
}
class Shuriken implements IShuriken {
public throw() {
return "hit!";
}
}
```
Now we are going to declare a class named FooBar, which has two dependencies (FooInterface & BarInterface). Note that the names of the arguments in the Inject decorator are significant because the injector uses these to look up the dependencies.
Now we are going to declare a class named `Ninja`, which has two dependencies (`IKatana` & `IShuriken`):
```
import { Inject } from "inversify";
@Inject("IKatana", "IShuriken")
class Ninja implements INinja {
@Inject("FooInterface", "BarInterface")
class FooBar implements FooBarInterface {
public foo : FooInterface;
public bar : BarInterface;
public log(){
console.log("foobar");
}
constructor(foo : FooInterface, bar : BarInterface) {
this.foo = foo;
this.bar = bar;
}
private _katana: IKatana;
private _shuriken: IShuriken;
public constructor(katana: IKatana, shuriken: IShuriken) {
this._katana = katana;
this._shuriken = shuriken;
}
public fight() { return this._katana.hit(); };
public sneak() { return this._shuriken.throw(); };
}

@@ -105,15 +113,18 @@ ```

Before we can start resolving and injecting dependencies we need to create an instance of the InversifyJS Kernel class. The Kernel will automatically detect is a class has some dependencies by examining its constructor. The Kernel will automatically detect if a class has some dependencies by examining the metadata provided by the Inject decorator.
Before we can start resolving and injecting dependencies we need to create an instance of the InversifyJS Kernel class.
The Kernel will automatically detect is a class has some dependencies by examining the `@Inject` annotation.
The Kernel will automatically detect if a class has some dependencies by examining the metadata provided by the Inject decorator.
```
import { Binding, BindingScope, Kernel } from "inversify";
import { Kernel } from "inversify";
var kernel = new Kernel();
```
In order to resolve a dependency, the kernel needs to be told which implementation type (classes) to associate with each service type (interfaces). We will use type bindings for this purpose. A type binding (or just a binding) is a mapping between a service type (an interface), and an implementation type (class).
In order to resolve a dependency, the kernel needs to be told which implementation type (classes) to associate with each service type (interfaces).
We will use type bindings for this purpose. A type binding (or just a binding) is a mapping between a service type (an interface), and an implementation type (class).
```
kernel.bind(new Binding<FooInterface>("FooInterface", Foo, BindingScope.Transient));
kernel.bind(new Binding<BarInterface>("BarInterface", Bar, BindingScope.Singleton));
kernel.bind(new Binding<FooBarInterface>("FooBarInterface", FooBar));
kernel.bind<INinja>("INinja").to(Ninja);
kernel.bind<IKatana>("IKatana").to(Katana);
kernel.bind<IShuriken>("IShuriken").to(Shuriken).inSingletonScope();
```

@@ -124,28 +135,33 @@

```
// Compilation error: Bar does not implement FooInterface
kernel.bind(new Binding<FooInterface>("FooInterface", Bar));
// Compilation error: Shuriken is not assignable to type IKatana
kernel.bind<IKatana>("IKatana").to(Shuriken);
```
We should keep the InversifyJS Kernel instantiation and type bindings centralized in one unique IoC configuration file. This will help us to abstract our application from the IoC configuration.
We should keep the InversifyJS Kernel instantiation and type bindings centralized in one unique IoC configuration file.
This will help us to abstract our application from the IoC configuration.
#### 3. Resolve & inject dependencies
After declaring the type bindings, we can invoke the kernel resolve method to resolve a dependency. We will use a string as the interface identifier (instead of the interface itself) because the TypeScript interfaces are not available at runtime.
After declaring the type bindings, we can invoke the kernel resolve method to resolve a dependency.
We will use a string as the interface identifier (instead of the interface itself) because the TypeScript interfaces are not available at runtime.
```
var foobar = kernel.resolve<FooBarInterface>("FooBarInterface");
let ninja = kernel.get<INinja>("INinja");
```
If the interface that we are trying to resolve is bind to a class that has some dependencies, InversifyJS will resolve and inject them into a new instance via the class constructor.
If the interface that we are trying to resolve is bind to a class that has some dependencies, InversifyJS will
resolve and inject them into a new instance via the class constructor.
```
// Foo and Bar instances has been injected into a new Foobar instance via its constructor
foobar.foo.log(); // foo
foobar.bar.log(); // bar
foobar.log(); // foobar
// Katana and Shuriken instances has been injected into a new Ninja instance via its constructor
expect(ninja.fight()).eql("cut!"); // true
expect(ninja.sneak()).eql("hit!"); // true
```
Our application dependency tree should have one unique root element, known as the application composition root, which is the only place where we should invoke the resolve method.
Our application dependency tree should have one unique root element, known as the application composition root, which is the
only place where we should invoke the resolve method.
Invoking resolve every time we need to inject something, as if it was a Service Locator is an anti-pattern. If we are working with an MVC framework the composition root should be located in the application class, somewhere along the routing logic or in a controller factory class. Please refer to the integration examples if you need additional help.
Invoking resolve every time we need to inject something, as if it was a Service Locator is an anti-pattern.
If we are working with an MVC framework the composition root should be located in the application class, somewhere
along the routing logic or in a controller factory class. Please refer to the integration examples if you need additional help.

@@ -152,0 +168,0 @@ # Integration with popular frameworks

@@ -17,2 +17,3 @@ "use strict";

}
exports.Inject = Inject;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Inject;

@@ -19,2 +19,2 @@ ///<reference path="../interfaces/interfaces.d.ts" />

export { Inject };
export default Inject;

@@ -9,2 +9,3 @@ "use strict";

}());
exports.Metadata = Metadata;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Metadata;

@@ -14,2 +14,2 @@ ///<reference path="../interfaces/interfaces.d.ts" />

export { Metadata };
export default Metadata;

@@ -6,6 +6,7 @@ "use strict";

return function (target, targetKey, index) {
var metadata = new metadata_1.Metadata("named", name);
var metadata = new metadata_1.default("named", name);
return decorator_utils_1.tagParameter(target, targetKey, index, metadata);
};
}
exports.Named = Named;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Named;
///<reference path="../interfaces/interfaces.d.ts" />
import { Metadata } from "../activation/metadata";
import Metadata from "../activation/metadata";
import { tagParameter } from "./decorator_utils";

@@ -14,2 +14,2 @@

export { Named };
export default Named;

@@ -17,2 +17,3 @@ "use strict";

}
exports.ParamNames = ParamNames;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = ParamNames;

@@ -19,2 +19,2 @@ ///<reference path="../interfaces/interfaces.d.ts" />

export { ParamNames };
export default ParamNames;

@@ -6,6 +6,7 @@ "use strict";

return function (target, targetKey, index) {
var metadata = new metadata_1.Metadata(metadataKey, metadataValue);
var metadata = new metadata_1.default(metadataKey, metadataValue);
return decorator_utils_1.tagParameter(target, targetKey, index, metadata);
};
}
exports.Tagged = Tagged;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Tagged;
///<reference path="../interfaces/interfaces.d.ts" />
import { Metadata } from "../activation/metadata";
import Metadata from "../activation/metadata";
import { tagParameter } from "./decorator_utils";

@@ -14,2 +14,2 @@

export { Tagged };
export default Tagged;
"use strict";
var BindingCountEnum;
(function (BindingCountEnum) {
BindingCountEnum[BindingCountEnum["NoBindingsAvailable"] = 0] = "NoBindingsAvailable";
BindingCountEnum[BindingCountEnum["OnlyOneBindingAvailable"] = 1] = "OnlyOneBindingAvailable";
BindingCountEnum[BindingCountEnum["MultipleBindingsAvailable"] = 2] = "MultipleBindingsAvailable";
})(BindingCountEnum || (BindingCountEnum = {}));
exports.BindingCountEnum = BindingCountEnum;
var BindingCount;
(function (BindingCount) {
BindingCount[BindingCount["NoBindingsAvailable"] = 0] = "NoBindingsAvailable";
BindingCount[BindingCount["OnlyOneBindingAvailable"] = 1] = "OnlyOneBindingAvailable";
BindingCount[BindingCount["MultipleBindingsAvailable"] = 2] = "MultipleBindingsAvailable";
})(BindingCount || (BindingCount = {}));
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = BindingCount;
///<reference path="../interfaces/interfaces.d.ts" />
enum BindingCountEnum {
enum BindingCount {
NoBindingsAvailable = 0,

@@ -9,2 +9,2 @@ OnlyOneBindingAvailable = 1,

export { BindingCountEnum };
export default BindingCount;

@@ -7,2 +7,3 @@ "use strict";

})(BindingScope || (BindingScope = {}));
exports.BindingScope = BindingScope;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = BindingScope;

@@ -8,2 +8,2 @@ ///<reference path="../interfaces/interfaces.d.ts" />

export { BindingScope };
export default BindingScope;
"use strict";
var binding_scope_1 = require("./binding_scope");
var binding_type_1 = require("./binding_type");
var Binding = (function () {
function Binding(runtimeIdentifier, implementationType, scopeType) {
function Binding(runtimeIdentifier) {
this.runtimeIdentifier = runtimeIdentifier;
this.implementationType = implementationType;
this.type = binding_type_1.default.Instance;
this.implementationType = null;
this.cache = null;
if (typeof scopeType === "undefined") {
this.scope = binding_scope_1.BindingScope.Transient;
}
else {
if (binding_scope_1.BindingScope[scopeType]) {
this.scope = scopeType;
}
else {
var msg = "Invalid scope type " + scopeType;
throw new Error(msg);
}
}
this.factory = null;
this.scope = binding_scope_1.default.Transient;
}
return Binding;
}());
exports.Binding = Binding;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Binding;

@@ -10,5 +10,6 @@ ///<reference path="../interfaces/interfaces.d.ts" />

import { BindingScope } from "./binding_scope";
import BindingScope from "./binding_scope";
import BindingType from "./binding_type";
class Binding<TService> implements IBinding<TService> {
class Binding<T> implements IBinding<T> {

@@ -18,7 +19,7 @@ // A runtime identifier because at runtime we don't have interfaces

// The constructor of a class which must implement TService
public implementationType: { new(): TService; };
// The constructor of a class which must implement T
public implementationType: { new(): T; };
// Cache used to allow singleton scope
public cache: TService;
// Cache used to allow singleton scope and BindingType.Value bindings
public cache: T;

@@ -28,24 +29,18 @@ // The scope mode to be used

constructor(
runtimeIdentifier: string,
implementationType: { new(...args: any[]): TService; },
scopeType?: BindingScope) {
// The kind of binding
public type: BindingType;
// A factory method used in BindingType.Factory bindings
public factory: (context) => T;
constructor(runtimeIdentifier: string) {
this.runtimeIdentifier = runtimeIdentifier;
this.implementationType = implementationType;
this.type = BindingType.Instance;
this.implementationType = null;
this.cache = null;
if (typeof scopeType === "undefined") {
this.scope = BindingScope.Transient; // default (Transient)
} else {
if (BindingScope[scopeType]) {
this.scope = scopeType;
} else {
let msg = `Invalid scope type ${scopeType}`;
throw new Error(msg);
}
}
this.factory = null;
this.scope = BindingScope.Transient;
}
}
export { Binding };
export default Binding;

@@ -9,1 +9,3 @@ "use strict";

exports.NOT_REGISTERED = "No bindigns found for service:";
exports.CIRCULAR_DEPENDENCY = "Circular dependency found between services:";
exports.NOT_IMPLEMENTED = "Sorry, this feature is not fully implemented yet";

@@ -10,1 +10,3 @@ ///<reference path="../interfaces/interfaces.d.ts" />

export const NOT_REGISTERED = "No bindigns found for service:";
export const CIRCULAR_DEPENDENCY = "Circular dependency found between services:";
export const NOT_IMPLEMENTED = "Sorry, this feature is not fully implemented yet";

@@ -1,6 +0,8 @@

interface IBinding<TService> {
interface IBinding<T> {
runtimeIdentifier: string;
implementationType: { new(): TService; };
cache: TService;
scope: number;
implementationType: { new(): T; };
factory: (context) => T;
cache: T;
scope: number; // BindingScope
type: number; // BindingType
}
/// <reference path="./kernel/kernel.d.ts" />
/// <reference path="./kernel/kernel_module.d.ts" />
/// <reference path="./kernel/kernel_options.d.ts" />
/// <reference path="./kernel/key_value_pair.d.ts" />

@@ -21,1 +23,5 @@ /// <reference path="./kernel/lookup.d.ts" />

/// <reference path="./middleware/middleware.d.ts" />
/// <reference path="./syntax/binding_when_syntax.d.ts" />
/// <reference path="./syntax/binding_to_syntax.d.ts" />
/// <reference path="./syntax/binding_in_syntax.d.ts" />
///<reference path="../interfaces.d.ts" />
interface IKernel {
bind(typeBinding: IBinding<any>): void;
bind<T>(runtimeIdentifier: string): IBindingToSyntax<T>;
unbind(runtimeIdentifier: string): void;

@@ -6,0 +6,0 @@ unbindAll(): void;

@@ -1,1 +0,3 @@

declare type Middleware = (...args: any[]) => any;
interface IMiddleware extends Function {
(...args: any[]): any;
}

@@ -8,2 +8,3 @@ ///<reference path="../bindings/binding.d.ts" />

createPlan(parentContext: IContext, binding: IBinding<any>): IPlan;
getBindings<T>(kernel: IKernel, service: string): IBinding<T>[];
}
"use strict";
var kernel_1 = require("./kernel/kernel");
exports.Kernel = kernel_1.Kernel;
var binding_1 = require("./bindings/binding");
exports.Binding = binding_1.Binding;
var binding_scope_1 = require("./bindings/binding_scope");
exports.BindingScope = binding_scope_1.BindingScope;
exports.Kernel = kernel_1.default;
var inject_1 = require("./activation/inject");
exports.Inject = inject_1.Inject;
exports.Inject = inject_1.default;
var tagged_1 = require("./activation/tagged");
exports.Tagged = tagged_1.Tagged;
exports.Tagged = tagged_1.default;
var named_1 = require("./activation/named");
exports.Named = named_1.Named;
exports.Named = named_1.default;
var paramnames_1 = require("./activation/paramnames");
exports.ParamNames = paramnames_1.ParamNames;
exports.ParamNames = paramnames_1.default;
var decorator_utils_1 = require("./activation/decorator_utils");
exports.decorate = decorator_utils_1.decorate;

@@ -8,18 +8,14 @@ ///<reference path="./interfaces/interfaces.d.ts" />

import { Kernel } from "./kernel/kernel";
import { Binding } from "./bindings/binding";
import { BindingScope } from "./bindings/binding_scope";
import { Inject } from "./activation/inject";
import { Tagged } from "./activation/tagged";
import { Named } from "./activation/named";
import { ParamNames } from "./activation/paramnames";
import Kernel from "./kernel/kernel";
import Inject from "./activation/inject";
import Tagged from "./activation/tagged";
import Named from "./activation/named";
import ParamNames from "./activation/paramnames";
import { decorate } from "./activation/decorator_utils";
export { Kernel };
export { Binding };
export { BindingScope };
export { decorate };
export { Inject };
export { decorate };
export { Tagged };
export { Named };
export { ParamNames };
"use strict";
var binding_count_1 = require("../bindings/binding_count");
var binding_1 = require("../bindings/binding");
var lookup_1 = require("./lookup");

@@ -7,12 +8,18 @@ var planner_1 = require("../planning/planner");

var ERROR_MSGS = require("../constants/error_msgs");
var binding_to_syntax_1 = require("../syntax/binding_to_syntax");
var Kernel = (function () {
function Kernel() {
var middleWare = [];
this._parentKernel = null;
this._planner = new planner_1.Planner();
this._resolver = new resolver_1.Resolver(middleWare);
this._bindingDictionary = new lookup_1.Lookup();
function Kernel(options) {
var _this = this;
if (options === void 0) { options = { middleware: [], modules: [] }; }
this._planner = new planner_1.default();
this._resolver = new resolver_1.default(options.middleware);
this._bindingDictionary = new lookup_1.default();
if (Array.isArray(options.modules) === true) {
options.modules.forEach(function (module) { module(_this); });
}
}
Kernel.prototype.bind = function (typeBinding) {
this._bindingDictionary.add(typeBinding.runtimeIdentifier, typeBinding);
Kernel.prototype.bind = function (runtimeIdentifier) {
var binding = new binding_1.default(runtimeIdentifier);
this._bindingDictionary.add(runtimeIdentifier, binding);
return new binding_to_syntax_1.default(binding);
};

@@ -28,12 +35,12 @@ Kernel.prototype.unbind = function (runtimeIdentifier) {

Kernel.prototype.unbindAll = function () {
this._bindingDictionary = new lookup_1.Lookup();
this._bindingDictionary = new lookup_1.default();
};
Kernel.prototype.get = function (runtimeIdentifier) {
var bindings = this._getBindingsByRuntimeIdentifier(runtimeIdentifier);
var bindings = this._planner.getBindings(this, runtimeIdentifier);
switch (bindings.length) {
case binding_count_1.BindingCountEnum.NoBindingsAvailable:
case binding_count_1.default.NoBindingsAvailable:
throw new Error(ERROR_MSGS.NOT_REGISTERED + " " + runtimeIdentifier);
case binding_count_1.BindingCountEnum.OnlyOneBindingAvailable:
case binding_count_1.default.OnlyOneBindingAvailable:
return this._planAndResolve(bindings[0]);
case binding_count_1.BindingCountEnum.MultipleBindingsAvailable:
case binding_count_1.default.MultipleBindingsAvailable:
default:

@@ -45,8 +52,8 @@ throw new Error(ERROR_MSGS.AMBIGUOUS_MATCH + " " + runtimeIdentifier);

var _this = this;
var bindings = this._getBindingsByRuntimeIdentifier(runtimeIdentifier);
var bindings = this._planner.getBindings(this, runtimeIdentifier);
switch (bindings.length) {
case binding_count_1.BindingCountEnum.NoBindingsAvailable:
case binding_count_1.default.NoBindingsAvailable:
throw new Error(ERROR_MSGS.NOT_REGISTERED + " " + runtimeIdentifier);
case binding_count_1.BindingCountEnum.OnlyOneBindingAvailable:
case binding_count_1.BindingCountEnum.MultipleBindingsAvailable:
case binding_count_1.default.OnlyOneBindingAvailable:
case binding_count_1.default.MultipleBindingsAvailable:
default:

@@ -58,13 +65,5 @@ return bindings.map(function (binding) {

};
Kernel.prototype._getBindingsByRuntimeIdentifier = function (runtimeIdentifier) {
var bindings = [];
if (this._bindingDictionary.hasKey(runtimeIdentifier)) {
bindings = this._bindingDictionary.get(runtimeIdentifier);
}
return bindings;
};
Kernel.prototype._planAndResolve = function (binding) {
var context = this._planner.createContext(this);
var plan = this._planner.createPlan(context, binding);
context.addPlan(plan);
this._planner.createPlan(context, binding);
return this._resolver.resolve(context);

@@ -74,2 +73,3 @@ };

}());
exports.Kernel = Kernel;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Kernel;

@@ -18,11 +18,12 @@ ///<reference path="../interfaces/interfaces.d.ts" />

import { BindingCountEnum } from "../bindings/binding_count";
import { Lookup } from "./lookup";
import { Planner } from "../planning/planner";
import { Resolver } from "../resolution/resolver";
import BindingCount from "../bindings/binding_count";
import Binding from "../bindings/binding";
import Lookup from "./lookup";
import Planner from "../planning/planner";
import Resolver from "../resolution/resolver";
import * as ERROR_MSGS from "../constants/error_msgs";
import BindingToSyntax from "../syntax/binding_to_syntax";
class Kernel implements IKernel {
private _parentKernel: IKernel;
private _planner: IPlanner;

@@ -33,13 +34,16 @@ private _resolver: IResolver;

// Initialize private properties
public constructor() {
let middleWare = [];
this._parentKernel = null;
public constructor(options: IKernelOptions = { middleware: [], modules: [] }) {
this._planner = new Planner();
this._resolver = new Resolver(middleWare);
this._resolver = new Resolver(options.middleware);
this._bindingDictionary = new Lookup<IBinding<any>>();
if (Array.isArray(options.modules) === true) {
options.modules.forEach((module) => { module(this); });
}
}
// Regiters a type binding
public bind(typeBinding: IBinding<any>): void {
this._bindingDictionary.add(typeBinding.runtimeIdentifier, typeBinding);
public bind<T>(runtimeIdentifier: string): IBindingToSyntax<T> {
let binding = new Binding<T>(runtimeIdentifier);
this._bindingDictionary.add(runtimeIdentifier, binding);
return new BindingToSyntax<T>(binding);
}

@@ -66,3 +70,3 @@

let bindings = this._getBindingsByRuntimeIdentifier<Service>(runtimeIdentifier);
let bindings = this._planner.getBindings<Service>(this, runtimeIdentifier);

@@ -72,11 +76,11 @@ switch (bindings.length) {

// CASE 1: There are no bindings
case BindingCountEnum.NoBindingsAvailable:
case BindingCount.NoBindingsAvailable:
throw new Error(`${ERROR_MSGS.NOT_REGISTERED} ${runtimeIdentifier}`);
// CASE 2: There is 1 binding
case BindingCountEnum.OnlyOneBindingAvailable:
// CASE 2: There is 1 binding
case BindingCount.OnlyOneBindingAvailable:
return this._planAndResolve<Service>(bindings[0]);
// CASE 3: There are multiple bindings throw as don't have enough information (metadata)
case BindingCountEnum.MultipleBindingsAvailable:
case BindingCount.MultipleBindingsAvailable:
default:

@@ -91,3 +95,3 @@ throw new Error(`${ERROR_MSGS.AMBIGUOUS_MATCH} ${runtimeIdentifier}`);

let bindings = this._getBindingsByRuntimeIdentifier<Service>(runtimeIdentifier);
let bindings = this._planner.getBindings<Service>(this, runtimeIdentifier);

@@ -97,8 +101,8 @@ switch (bindings.length) {

// CASE 1: There are no bindings
case BindingCountEnum.NoBindingsAvailable:
case BindingCount.NoBindingsAvailable:
throw new Error(`${ERROR_MSGS.NOT_REGISTERED} ${runtimeIdentifier}`);
// CASE 2: There is AT LEAST 1 binding
case BindingCountEnum.OnlyOneBindingAvailable:
case BindingCountEnum.MultipleBindingsAvailable:
case BindingCount.OnlyOneBindingAvailable:
case BindingCount.MultipleBindingsAvailable:
default:

@@ -111,11 +115,2 @@ return bindings.map((binding) => {

// Returns all the available bindings for a selected runtime identifier
private _getBindingsByRuntimeIdentifier<Service>(runtimeIdentifier: string): IBinding<Service>[] {
let bindings: IBinding<Service>[] = [];
if (this._bindingDictionary.hasKey(runtimeIdentifier)) {
bindings = this._bindingDictionary.get(runtimeIdentifier);
}
return bindings;
}
// Generates an executes a resolution plan

@@ -128,7 +123,4 @@ private _planAndResolve<Service>(binding: IBinding<Service>): Service {

// STEP 2: generate a resolutioin plan and link it to the context
let plan = this._planner.createPlan(context, binding);
this._planner.createPlan(context, binding);
// Plan and Context are duable linked
context.addPlan(plan);
// STEP 3: execute resolution plan

@@ -140,2 +132,2 @@ return this._resolver.resolve<Service>(context);

export { Kernel };
export default Kernel;

@@ -10,2 +10,3 @@ "use strict";

}());
exports.KeyValuePair = KeyValuePair;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = KeyValuePair;

@@ -15,2 +15,2 @@ ///<reference path="../interfaces/interfaces.d.ts" />

export { KeyValuePair };
export default KeyValuePair;

@@ -22,3 +22,3 @@ "use strict";

else {
this._dictionary.push(new key_value_pair_1.KeyValuePair(key, value));
this._dictionary.push(new key_value_pair_1.default(key, value));
}

@@ -74,2 +74,3 @@ };

}());
exports.Lookup = Lookup;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Lookup;

@@ -8,3 +8,3 @@ ///<reference path="../interfaces/interfaces.d.ts" />

import { KeyValuePair } from "./key_value_pair";
import KeyValuePair from "./key_value_pair";
import * as ERROR_MSGS from "../constants/error_msgs";

@@ -88,2 +88,2 @@

export { Lookup };
export default Lookup;

@@ -11,2 +11,3 @@ "use strict";

}());
exports.Context = Context;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Context;

@@ -17,2 +17,2 @@ ///<reference path="../interfaces/interfaces.d.ts" />

export { Context };
export default Context;

@@ -9,2 +9,3 @@ "use strict";

}());
exports.Plan = Plan;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Plan;
///<reference path="../interfaces/interfaces.d.ts" />
// import { Context } from "./context";
// import { Request } from "./request";
// import { Target } from "./target";
class Plan implements IPlan {

@@ -18,2 +14,2 @@

export { Plan };
export default Plan;

@@ -13,34 +13,66 @@ "use strict";

Planner.prototype.createContext = function (kernel) {
return new context_1.Context(kernel);
return new context_1.default(kernel);
};
Planner.prototype.createPlan = function (context, binding) {
var _this = this;
var rootRequest = new request_1.Request(binding.runtimeIdentifier, context, null, binding);
var rootRequest = new request_1.default(binding.runtimeIdentifier, context, null, binding);
rootRequest.bindings.push(binding);
var plan = new plan_1.Plan(context, rootRequest);
var plan = new plan_1.default(context, rootRequest);
context.addPlan(plan);
var dependencies = this._getDependencies(binding.implementationType);
dependencies.forEach(function (d) {
_this._createSubRequest(rootRequest, d);
});
dependencies.forEach(function (d) { _this._createSubRequest(rootRequest, d); });
return plan;
};
Planner.prototype.getBindings = function (kernel, service) {
var bindings = [];
var _kernel = kernel;
var _bindingDictionary = _kernel._bindingDictionary;
if (_bindingDictionary.hasKey(service)) {
bindings = _bindingDictionary.get(service);
}
return bindings;
};
Planner.prototype._createSubRequest = function (parentRequest, target) {
var _this = this;
var bindings = this._getBindings(parentRequest.parentContext, target.service.value());
if (bindings.length > 1) {
throw new Error(ERROR_MSGS.AMBIGUOUS_MATCH + " " + target.service.value());
try {
var bindings = this.getBindings(parentRequest.parentContext.kernel, target.service.value());
if (bindings.length > 1) {
throw new Error(ERROR_MSGS.AMBIGUOUS_MATCH + " " + target.service.value());
}
else {
var binding = bindings[0];
var childRequest_1 = parentRequest.addChildRequest(target.service.value(), binding, target);
var subDependencies = this._getDependencies(binding.implementationType);
subDependencies.forEach(function (d, index) {
_this._createSubRequest(childRequest_1, d);
});
}
}
else {
var binding = bindings[0];
var childRequest_1 = parentRequest.addChildRequest(target.service.value(), binding, target);
var subDependencies = this._getDependencies(binding.implementationType);
subDependencies.forEach(function (d, index) {
_this._createSubRequest(childRequest_1, d);
});
catch (error) {
if (error instanceof RangeError) {
this._throwWhenCircularDependenciesFound(parentRequest.parentContext.plan.rootRequest);
}
else {
throw new Error(error.message);
}
}
};
Planner.prototype._getBindings = function (context, service) {
var kernel = context.kernel;
var bindingDictionary = kernel._bindingDictionary;
return bindingDictionary.get(service);
Planner.prototype._throwWhenCircularDependenciesFound = function (request, previousServices) {
var _this = this;
if (previousServices === void 0) { previousServices = []; }
previousServices.push(request.service);
request.childRequests.forEach(function (childRequest) {
var service = childRequest.service;
if (previousServices.indexOf(service) === -1) {
if (childRequest.childRequests.length > 0) {
_this._throwWhenCircularDependenciesFound(childRequest, previousServices);
}
else {
previousServices.push(service);
}
}
else {
throw new Error(ERROR_MSGS.CIRCULAR_DEPENDENCY + " " + service + " and " + request.service);
}
});
};

@@ -53,3 +85,3 @@ Planner.prototype._getDependencies = function (func) {

var targetName = paramNames[index];
var target = new target_1.Target(targetName, inject);
var target = new target_1.default(targetName, inject);
target.metadata = tags[index.toString()] || [];

@@ -61,2 +93,3 @@ return target;

}());
exports.Planner = Planner;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Planner;
///<reference path="../interfaces/interfaces.d.ts" />
import "reflect-metadata";
import { Plan } from "./plan";
import { Context } from "./context";
import { Request } from "./request";
import { Target } from "./target";
import Plan from "./plan";
import Context from "./context";
import Request from "./request";
import Target from "./target";
import * as METADATA_KEY from "../constants/metadata_keys";

@@ -28,41 +28,73 @@ import * as ERROR_MSGS from "../constants/error_msgs";

// Plan and Context are duable linked
context.addPlan(plan);
let dependencies = this._getDependencies(binding.implementationType);
dependencies.forEach((d) => {
this._createSubRequest(rootRequest, d);
});
dependencies.forEach((d) => { this._createSubRequest(rootRequest, d); });
return plan;
}
public getBindings<T>(kernel: IKernel, service: string): IBinding<T>[] {
let bindings: IBinding<T>[] = [];
let _kernel: any = kernel;
let _bindingDictionary = _kernel._bindingDictionary;
if (_bindingDictionary.hasKey(service)) {
bindings = _bindingDictionary.get(service);
}
return bindings;
}
private _createSubRequest(parentRequest: IRequest, target: ITarget) {
let bindings = this._getBindings(parentRequest.parentContext, target.service.value());
try {
let bindings = this.getBindings<any>(parentRequest.parentContext.kernel, target.service.value());
// mutiple bindings available
if (bindings.length > 1) {
// mutiple bindings available
if (bindings.length > 1) {
// TODO 2.0.0-alpha.3
// TODO handle multi-injection, named, tagged and contextual binsingd here
throw new Error(`${ERROR_MSGS.AMBIGUOUS_MATCH} ${target.service.value()}`);
// TODO 2.0.0-alpha.3
// TODO handle multi-injection, named, tagged and contextual binsingd here
throw new Error(`${ERROR_MSGS.AMBIGUOUS_MATCH} ${target.service.value()}`);
} else {
} else {
// TODO 2.0.0-alpha.2 handle value, factory, etc here
let binding = bindings[0];
// TODO 2.0.0-alpha.2 handle value, factory, etc here
let binding = bindings[0];
let childRequest = parentRequest.addChildRequest(target.service.value(), binding, target);
let childRequest = parentRequest.addChildRequest(target.service.value(), binding, target);
let subDependencies = this._getDependencies(binding.implementationType);
let subDependencies = this._getDependencies(binding.implementationType);
subDependencies.forEach((d, index) => {
this._createSubRequest(childRequest, d);
});
subDependencies.forEach((d, index) => {
this._createSubRequest(childRequest, d);
});
}
} catch (error) {
if (error instanceof RangeError) {
this._throwWhenCircularDependenciesFound(parentRequest.parentContext.plan.rootRequest);
} else {
throw new Error(error.message);
}
}
}
private _getBindings(context: IContext, service: string) {
let kernel: any = context.kernel;
let bindingDictionary: ILookup<IBinding<any>> = kernel._bindingDictionary;
return bindingDictionary.get(service);
private _throwWhenCircularDependenciesFound(request: IRequest, previousServices: string[] = []) {
previousServices.push(request.service);
request.childRequests.forEach((childRequest) => {
let service = childRequest.service;
if (previousServices.indexOf(service) === -1) {
if (childRequest.childRequests.length > 0) {
this._throwWhenCircularDependenciesFound(childRequest, previousServices);
} else {
previousServices.push(service);
}
} else {
throw new Error(`${ERROR_MSGS.CIRCULAR_DEPENDENCY} ${service} and ${request.service}`);
}
});
}

@@ -85,2 +117,2 @@

export { Planner };
export default Planner;

@@ -26,2 +26,3 @@ "use strict";

}());
exports.QueryableString = QueryableString;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = QueryableString;

@@ -36,2 +36,2 @@ ///<reference path="../interfaces/interfaces.d.ts" />

export { QueryableString };
export default QueryableString;

@@ -29,2 +29,3 @@ "use strict";

}());
exports.Request = Request;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Request;

@@ -57,2 +57,2 @@ ///<reference path="../interfaces/interfaces.d.ts" />

export { Request };
export default Request;

@@ -6,10 +6,10 @@ "use strict";

function Target(name, service, namedOrTagged) {
this.name = new queryable_string_1.QueryableString(name);
this.service = new queryable_string_1.QueryableString(service);
this.name = new queryable_string_1.default(name);
this.service = new queryable_string_1.default(service);
this.metadata = new Array();
var metadataItem = null;
if (typeof namedOrTagged === "string") {
metadataItem = new metadata_1.Metadata("named", namedOrTagged);
metadataItem = new metadata_1.default("named", namedOrTagged);
}
else if (namedOrTagged instanceof metadata_1.Metadata) {
else if (namedOrTagged instanceof metadata_1.default) {
metadataItem = namedOrTagged;

@@ -62,2 +62,3 @@ }

}());
exports.Target = Target;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Target;
///<reference path="../interfaces/interfaces.d.ts" />
import { Metadata } from "../activation/metadata";
import { QueryableString } from "./queryable_string";
import Metadata from "../activation/metadata";
import QueryableString from "./queryable_string";

@@ -78,2 +78,2 @@ class Target implements ITarget {

export { Target };
export default Target;

@@ -17,3 +17,3 @@ "use strict";

var constr = binding.implementationType;
var isSingleton = binding.scope === binding_scope_1.BindingScope.Singleton;
var isSingleton = binding.scope === binding_scope_1.default.Singleton;
if (isSingleton && binding.cache !== null) {

@@ -45,2 +45,3 @@ return binding.cache;

}());
exports.Resolver = Resolver;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Resolver;
///<reference path="../interfaces/interfaces.d.ts" />
import { BindingScope } from "../bindings/binding_scope";
import BindingScope from "../bindings/binding_scope";
class Resolver implements IResolver {
private _middleWare: Middleware[];
private _middleWare: IMiddleware[];
public constructor(middleWare: Middleware[] = []) {
public constructor(middleWare: IMiddleware[] = []) {
this._middleWare = middleWare;

@@ -49,2 +49,2 @@ }

export { Resolver };
export default Resolver;

@@ -12,53 +12,55 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {

(function (inversify_global_test) {
var Foo = (function () {
function Foo() {
this.name = "foo";
var Katana = (function () {
function Katana() {
}
Foo.prototype.greet = function () {
return this.name;
Katana.prototype.hit = function () {
return "cut!";
};
return Foo;
return Katana;
}());
var Bar = (function () {
function Bar() {
this.name = "bar";
var Shuriken = (function () {
function Shuriken() {
}
Bar.prototype.greet = function () {
return this.name;
Shuriken.prototype.throw = function () {
return "hit!";
};
return Bar;
return Shuriken;
}());
var Inject = inversify.Inject;
var FooBar = (function () {
function FooBar(foo, bar) {
this.foo = foo;
this.bar = bar;
var Ninja = (function () {
function Ninja(katana, shuriken) {
this._katana = katana;
this._shuriken = shuriken;
}
FooBar.prototype.greet = function () {
return this.foo.greet() + this.bar.greet();
};
FooBar = __decorate([
Inject("FooInterface", "BarInterface"),
Ninja.prototype.fight = function () { return this._katana.hit(); };
;
Ninja.prototype.sneak = function () { return this._shuriken.throw(); };
;
Ninja = __decorate([
Inject("IKatana", "IShuriken"),
__metadata('design:paramtypes', [Object, Object])
], FooBar);
return FooBar;
], Ninja);
return Ninja;
}());
var kernel = new inversify.Kernel();
var fooRuntimeIdentifier = "FooInterface";
var barRuntimeIdentifier = "BarInterface";
var fooBarRuntimeIdentifier = "FooBarInterface";
var fooBinding = new inversify.Binding(fooRuntimeIdentifier, Foo);
var barBinding = new inversify.Binding(barRuntimeIdentifier, Bar);
var fooBarBinding = new inversify.Binding(fooBarRuntimeIdentifier, FooBar, inversify.BindingScope.Singleton);
kernel.bind(fooBinding);
kernel.bind(barBinding);
kernel.bind(fooBarBinding);
var foo = kernel.get(fooRuntimeIdentifier);
var bar = kernel.get(barRuntimeIdentifier);
var fooBar = kernel.get(fooBarRuntimeIdentifier);
console.log(foo);
console.log(bar);
console.log(fooBar);
kernel.unbind(fooRuntimeIdentifier);
kernel.unbindAll();
var Kernel = inversify.Kernel;
var kernel1 = new Kernel();
kernel1.bind("INinja").to(Ninja);
kernel1.bind("IKatana").to(Katana);
kernel1.bind("IShuriken").to(Shuriken).inSingletonScope();
var ninja = kernel1.get("INinja");
console.log(ninja);
kernel1.unbind("INinja");
kernel1.unbindAll();
var module = function (kernel) {
kernel.bind("INinja").to(Ninja);
kernel.bind("IKatana").to(Katana);
kernel.bind("IShuriken").to(Shuriken).inSingletonScope();
};
var options = {
middleware: [],
modules: [module]
};
var kernel2 = new Kernel(options);
var ninja2 = kernel2.get("INinja");
console.log(ninja2);
})(inversify_global_test || (inversify_global_test = {}));

@@ -5,36 +5,25 @@ /// <reference path="inversify-global.d.ts" />

interface FooInterface {
name: string;
greet(): string;
interface INinja {
fight(): string;
sneak(): string;
}
interface BarInterface {
name: string;
greet(): string;
interface IKatana {
hit(): string;
}
interface FooBarInterface {
foo: FooInterface;
bar: BarInterface;
greet(): string;
interface IShuriken {
throw();
}
class Foo implements FooInterface {
public name: string;
constructor() {
this.name = "foo";
class Katana implements IKatana {
public hit() {
return "cut!";
}
public greet(): string {
return this.name;
}
}
class Bar implements BarInterface {
public name: string;
constructor() {
this.name = "bar";
class Shuriken implements IShuriken {
public throw() {
return "hit!";
}
public greet(): string {
return this.name;
}
}

@@ -44,45 +33,48 @@

@Inject("FooInterface", "BarInterface")
class FooBar implements FooBarInterface {
public foo: FooInterface;
public bar: BarInterface;
constructor(foo: FooInterface, bar: BarInterface) {
this.foo = foo;
this.bar = bar;
@Inject("IKatana", "IShuriken")
class Ninja implements INinja {
private _katana: IKatana;
private _shuriken: IShuriken;
public constructor(katana: IKatana, shuriken: IShuriken) {
this._katana = katana;
this._shuriken = shuriken;
}
public greet(): string {
return this.foo.greet() + this.bar.greet();
}
public fight() { return this._katana.hit(); };
public sneak() { return this._shuriken.throw(); };
}
// Kernel
let kernel = new inversify.Kernel();
let Kernel = inversify.Kernel;
// Identifiers
let fooRuntimeIdentifier = "FooInterface";
let barRuntimeIdentifier = "BarInterface";
let fooBarRuntimeIdentifier = "FooBarInterface";
let kernel1 = new Kernel();
kernel1.bind<INinja>("INinja").to(Ninja);
kernel1.bind<IKatana>("IKatana").to(Katana);
kernel1.bind<IShuriken>("IShuriken").to(Shuriken).inSingletonScope();
// Bindings
let fooBinding = new inversify.Binding<FooInterface>(fooRuntimeIdentifier, Foo);
let barBinding = new inversify.Binding<BarInterface>(barRuntimeIdentifier, Bar);
let fooBarBinding = new inversify.Binding<FooBarInterface>(fooBarRuntimeIdentifier, FooBar, inversify.BindingScope.Singleton);
let ninja = kernel1.get<INinja>("INinja");
console.log(ninja);
kernel.bind(fooBinding);
kernel.bind(barBinding);
kernel.bind(fooBarBinding);
// Unbind
kernel1.unbind("INinja");
kernel1.unbindAll();
// Resolve
let foo = kernel.get<Foo>(fooRuntimeIdentifier);
let bar = kernel.get<Bar>(barRuntimeIdentifier);
let fooBar = kernel.get<FooBar>(fooBarRuntimeIdentifier);
// Kernel modules
let module: inversify.IKernelModule = (kernel: inversify.IKernel) => {
kernel.bind<INinja>("INinja").to(Ninja);
kernel.bind<IKatana>("IKatana").to(Katana);
kernel.bind<IShuriken>("IShuriken").to(Shuriken).inSingletonScope();
};
console.log(foo);
console.log(bar);
console.log(fooBar);
let options: inversify.IKernelOptions = {
middleware: [],
modules: [module]
};
// Unbind
kernel.unbind(fooRuntimeIdentifier);
kernel.unbindAll();
let kernel2 = new Kernel(options);
let ninja2 = kernel2.get<INinja>("INinja");
console.log(ninja2);
}

@@ -8,42 +8,123 @@ // Type definitions for inversify 1.2.2

interface BindingInterface<TServiceType> {
runtimeIdentifier: string;
implementationType: { new(): TServiceType ; };
cache: TServiceType;
scope: number; // TypeBindingScopeEnum
}
export interface IMiddleware extends Function {
(...args: any[]): any;
}
interface KernelInterface {
bind(typeBinding: BindingInterface<any>): void;
unbind(runtimeIdentifier: string): void;
unbindAll(): void;
get<Service>(runtimeIdentifier: string): Service;
}
export interface IKernelModule extends Function {
(kernel: IKernel): void;
}
export enum BindingScope {
Transient = 0,
Singleton = 1,
}
export interface IKernelOptions {
middleware?: IMiddleware[];
modules?: IKernelModule[];
}
export class Binding<TServiceType> implements BindingInterface<TServiceType> {
public runtimeIdentifier: string;
public implementationType: {
new (): TServiceType;
};
public cache: TServiceType;
public scope: BindingScope;
constructor(runtimeIdentifier: string, implementationType: {
new (...args: any[]): TServiceType;
}, scopeType?: BindingScope);
}
export interface IKernelConstructor {
new(options?: IKernelOptions): IKernel;
}
export class Kernel implements KernelInterface {
public bind(typeBinding: BindingInterface<any>): void;
public unbind(runtimeIdentifier: string): void;
public unbindAll(): void;
public get<Service>(runtimeIdentifier: string): Service;
constructor();
}
export interface IKernel {
bind<T>(runtimeIdentifier: string): IBindingToSyntax<T>;
unbind(runtimeIdentifier: string): void;
unbindAll(): void;
get<Service>(runtimeIdentifier: string): Service;
getAll<Service>(runtimeIdentifier: string): Service[];
}
export function Inject(...typeIdentifiers: string[]): (typeConstructor: any) => void;
interface IBindingWhenSyntax<T> {
when(constraint: Constraint): void;
}
interface IBindingToSyntax<T> {
to(constructor: { new(...args: any[]): T; }): IBindingInSyntax<T>;
toValue(value: T): IBindingWhenSyntax<T>;
toConstructor(constructor: { new(...args: any[]): T; }): IBindingWhenSyntax<T>;
toFactory(factory: (context) => T): IBindingWhenSyntax<T>;
}
interface IBindingInSyntax<T> {
inTransientScope(): IBindingWhenSyntax<T>;
inSingletonScope(): IBindingWhenSyntax<T>;
}
export interface IBinding<T> {
runtimeIdentifier: string;
implementationType: { new(): T; };
factory: (context) => T;
cache: T;
scope: number; // BindingScope
type: number; // BindingType
}
export interface IContext {
/// Gets the kernel that is driving the activation.
kernel: IKernel;
/// Gets or sets the activation plan.
plan: IPlan;
addPlan(plan: IPlan);
}
export interface IMetadata {
key: string;
value: any;
}
export interface IPlan {
parentContext: IContext;
rootRequest: IRequest;
}
export interface ITarget {
service: IQueryableString;
name: IQueryableString;
metadata: Array<IMetadata>;
isArray(): boolean;
isNamed(): boolean;
isTagged(): boolean;
matchesName(name: string): boolean;
matchesTag(name: IMetadata): boolean;
}
export interface IQueryableString {
startsWith(searchString: string): boolean;
endsWith(searchString: string): boolean;
contains(searchString: string): boolean;
equals(compareString: string): boolean;
value(): string;
}
export interface IRequest {
/// The service that was requested.
service: string;
/// The parent context.
parentContext: IContext;
/// The parent request.
parentRequest: IRequest;
// The child requests
childRequests: IRequest[];
/// Gets the target that will receive the injection, if any.
target: ITarget;
/// Gets the stack of bindings which have been activated by this request.
bindings: IBinding<any>[];
// Adds a child request to the request
addChildRequest(
service: string,
bindings: (IBinding<any>|IBinding<any>[]),
target: ITarget): IRequest;
}
export type Constraint = (request: IRequest) => boolean;
export var Kernel: IKernelConstructor;
export function Inject(...typeIdentifiers: string[]): (typeConstructor: any) => void;
}

@@ -6,41 +6,122 @@ // Type definitions for inversify 1.2.2

interface BindingInterface<TServiceType> {
runtimeIdentifier: string;
implementationType: { new(): TServiceType ; };
cache: TServiceType;
scope: number; // TypeBindingScopeEnum
interface IMiddleware extends Function {
(...args: any[]): any;
}
interface KernelInterface {
bind(typeBinding: BindingInterface<any>): void;
unbind(runtimeIdentifier: string): void;
unbindAll(): void;
get<Service>(runtimeIdentifier: string): Service;
interface IKernelModule extends Function {
(kernel: IKernel): void;
}
export enum BindingScope {
Transient = 0,
Singleton = 1,
interface IKernelOptions {
middleware?: IMiddleware[];
modules?: IKernelModule[];
}
export class Binding<TServiceType> implements BindingInterface<TServiceType> {
public runtimeIdentifier: string;
public implementationType: {
new (): TServiceType;
};
public cache: TServiceType;
public scope: BindingScope;
constructor(runtimeIdentifier: string, implementationType: {
new (...args: any[]): TServiceType;
}, scopeType?: BindingScope);
interface IKernelConstructor {
new(options?: IKernelOptions): IKernel;
}
export class Kernel implements KernelInterface {
public bind(typeBinding: BindingInterface<any>): void;
public unbind(runtimeIdentifier: string): void;
public unbindAll(): void;
public get<Service>(runtimeIdentifier: string): Service;
constructor();
interface IKernel {
bind<T>(runtimeIdentifier: string): IBindingToSyntax<T>;
unbind(runtimeIdentifier: string): void;
unbindAll(): void;
get<Service>(runtimeIdentifier: string): Service;
getAll<Service>(runtimeIdentifier: string): Service[];
}
interface IBindingWhenSyntax<T> {
when(constraint: Constraint): void;
}
interface IBindingToSyntax<T> {
to(constructor: { new(...args: any[]): T; }): IBindingInSyntax<T>;
toValue(value: T): IBindingWhenSyntax<T>;
toConstructor(constructor: { new(...args: any[]): T; }): IBindingWhenSyntax<T>;
toFactory(factory: (context) => T): IBindingWhenSyntax<T>;
}
interface IBindingInSyntax<T> {
inTransientScope(): IBindingWhenSyntax<T>;
inSingletonScope(): IBindingWhenSyntax<T>;
}
interface IBinding<T> {
runtimeIdentifier: string;
implementationType: { new(): T; };
factory: (context) => T;
cache: T;
scope: number; // BindingScope
type: number; // BindingType
}
interface IMetadata {
key: string;
value: any;
}
interface IContext {
/// Gets the kernel that is driving the activation.
kernel: IKernel;
/// Gets or sets the activation plan.
plan: IPlan;
addPlan(plan: IPlan);
}
interface IPlan {
parentContext: IContext;
rootRequest: IRequest;
}
interface ITarget {
service: IQueryableString;
name: IQueryableString;
metadata: Array<IMetadata>;
isArray(): boolean;
isNamed(): boolean;
isTagged(): boolean;
matchesName(name: string): boolean;
matchesTag(name: IMetadata): boolean;
}
interface IQueryableString {
startsWith(searchString: string): boolean;
endsWith(searchString: string): boolean;
contains(searchString: string): boolean;
equals(compareString: string): boolean;
value(): string;
}
interface IRequest {
/// The service that was requested.
service: string;
/// The parent context.
parentContext: IContext;
/// The parent request.
parentRequest: IRequest;
// The child requests
childRequests: IRequest[];
/// Gets the target that will receive the injection, if any.
target: ITarget;
/// Gets the stack of bindings which have been activated by this request.
bindings: IBinding<any>[];
// Adds a child request to the request
addChildRequest(
service: string,
bindings: (IBinding<any>|IBinding<any>[]),
target: ITarget): IRequest;
}
declare type Constraint = (request: IRequest) => boolean;
export var Kernel: IKernelConstructor;
export function Inject(...typeIdentifiers: string[]): (typeConstructor: any) => void;

@@ -14,52 +14,53 @@ "use strict";

(function (inversify_external_module_test) {
var Foo = (function () {
function Foo() {
this.name = "foo";
var Katana = (function () {
function Katana() {
}
Foo.prototype.greet = function () {
return this.name;
Katana.prototype.hit = function () {
return "cut!";
};
return Foo;
return Katana;
}());
var Bar = (function () {
function Bar() {
this.name = "bar";
var Shuriken = (function () {
function Shuriken() {
}
Bar.prototype.greet = function () {
return this.name;
Shuriken.prototype.throw = function () {
return "hit!";
};
return Bar;
return Shuriken;
}());
var FooBar = (function () {
function FooBar(foo, bar) {
this.foo = foo;
this.bar = bar;
var Ninja = (function () {
function Ninja(katana, shuriken) {
this._katana = katana;
this._shuriken = shuriken;
}
FooBar.prototype.greet = function () {
return this.foo.greet() + this.bar.greet();
};
FooBar = __decorate([
inversify_1.Inject("FooInterface", "BarInterface"),
Ninja.prototype.fight = function () { return this._katana.hit(); };
;
Ninja.prototype.sneak = function () { return this._shuriken.throw(); };
;
Ninja = __decorate([
inversify_1.Inject("IKatana", "IShuriken"),
__metadata('design:paramtypes', [Object, Object])
], FooBar);
return FooBar;
], Ninja);
return Ninja;
}());
var kernel = new inversify_1.Kernel();
var fooRuntimeIdentifier = "FooInterface";
var barRuntimeIdentifier = "BarInterface";
var fooBarRuntimeIdentifier = "FooBarInterface";
var fooBinding = new inversify_1.Binding(fooRuntimeIdentifier, Foo);
var barBinding = new inversify_1.Binding(barRuntimeIdentifier, Bar);
var fooBarBinding = new inversify_1.Binding(fooBarRuntimeIdentifier, FooBar, inversify_1.BindingScope.Singleton);
kernel.bind(fooBinding);
kernel.bind(barBinding);
kernel.bind(fooBarBinding);
var foo = kernel.get(fooRuntimeIdentifier);
var bar = kernel.get(barRuntimeIdentifier);
var fooBar = kernel.get(fooBarRuntimeIdentifier);
console.log(foo);
console.log(bar);
console.log(fooBar);
kernel.unbind(fooRuntimeIdentifier);
kernel.unbindAll();
var kernel1 = new inversify_1.Kernel();
kernel1.bind("INinja").to(Ninja);
kernel1.bind("IKatana").to(Katana);
kernel1.bind("IShuriken").to(Shuriken).inSingletonScope();
var ninja = kernel1.get("INinja");
console.log(ninja);
kernel1.unbind("INinja");
kernel1.unbindAll();
var module = function (kernel) {
kernel.bind("INinja").to(Ninja);
kernel.bind("IKatana").to(Katana);
kernel.bind("IShuriken").to(Shuriken).inSingletonScope();
};
var options = {
middleware: [],
modules: [module]
};
var kernel2 = new inversify_1.Kernel(options);
var ninja2 = kernel2.get("INinja");
console.log(ninja2);
})(inversify_external_module_test || (inversify_external_module_test = {}));
/// <reference path="inversify.d.ts" />
import { BindingScope, Binding, Kernel, Inject } from "inversify";
import { Kernel, Inject, IKernel, IKernelOptions, IKernelModule } from "inversify";
module inversify_external_module_test {
interface FooInterface {
name: string;
greet(): string;
interface INinja {
fight(): string;
sneak(): string;
}
interface BarInterface {
name: string;
greet(): string;
interface IKatana {
hit(): string;
}
interface FooBarInterface {
foo: FooInterface;
bar: BarInterface;
greet(): string;
interface IShuriken {
throw();
}
class Foo implements FooInterface {
public name: string;
constructor() {
this.name = "foo";
class Katana implements IKatana {
public hit() {
return "cut!";
}
public greet(): string {
return this.name;
}
}
class Bar implements BarInterface {
public name: string;
constructor() {
this.name = "bar";
class Shuriken implements IShuriken {
public throw() {
return "hit!";
}
public greet(): string {
return this.name;
}
}
@Inject("FooInterface", "BarInterface")
class FooBar implements FooBarInterface {
public foo: FooInterface;
public bar: BarInterface;
constructor(foo: FooInterface, bar: BarInterface) {
this.foo = foo;
this.bar = bar;
@Inject("IKatana", "IShuriken")
class Ninja implements INinja {
private _katana: IKatana;
private _shuriken: IShuriken;
public constructor(katana: IKatana, shuriken: IShuriken) {
this._katana = katana;
this._shuriken = shuriken;
}
public greet(): string {
return this.foo.greet() + this.bar.greet();
}
public fight() { return this._katana.hit(); };
public sneak() { return this._shuriken.throw(); };
}
// Kernel
let kernel = new Kernel();
let kernel1 = new Kernel();
kernel1.bind<INinja>("INinja").to(Ninja);
kernel1.bind<IKatana>("IKatana").to(Katana);
kernel1.bind<IShuriken>("IShuriken").to(Shuriken).inSingletonScope();
// Identifiers
let fooRuntimeIdentifier = "FooInterface";
let barRuntimeIdentifier = "BarInterface";
let fooBarRuntimeIdentifier = "FooBarInterface";
let ninja = kernel1.get<INinja>("INinja");
console.log(ninja);
// Bindings
let fooBinding = new Binding<FooInterface>(fooRuntimeIdentifier, Foo);
let barBinding = new Binding<BarInterface>(barRuntimeIdentifier, Bar);
let fooBarBinding = new Binding<FooBarInterface>(fooBarRuntimeIdentifier, FooBar, BindingScope.Singleton);
// Unbind
kernel1.unbind("INinja");
kernel1.unbindAll();
kernel.bind(fooBinding);
kernel.bind(barBinding);
kernel.bind(fooBarBinding);
// Kernel modules
let module: IKernelModule = (kernel: IKernel) => {
kernel.bind<INinja>("INinja").to(Ninja);
kernel.bind<IKatana>("IKatana").to(Katana);
kernel.bind<IShuriken>("IShuriken").to(Shuriken).inSingletonScope();
};
// Resolve
let foo = kernel.get<Foo>(fooRuntimeIdentifier);
let bar = kernel.get<Bar>(barRuntimeIdentifier);
let fooBar = kernel.get<FooBar>(fooBarRuntimeIdentifier);
let options: IKernelOptions = {
middleware: [],
modules: [module]
};
console.log(foo);
console.log(bar);
console.log(fooBar);
let kernel2 = new Kernel(options);
let ninja2 = kernel2.get<INinja>("INinja");
console.log(ninja2);
// Unbind
kernel.unbind(fooRuntimeIdentifier);
kernel.unbindAll();
}

@@ -8,43 +8,123 @@ // Type definitions for inversify 1.2.2

interface BindingInterface<TServiceType> {
runtimeIdentifier: string;
implementationType: { new(): TServiceType ; };
cache: TServiceType;
scope: number; // TypeBindingScopeEnum
}
export interface IMiddleware extends Function {
(...args: any[]): any;
}
interface KernelInterface {
bind(typeBinding: BindingInterface<any>): void;
unbind(runtimeIdentifier: string): void;
unbindAll(): void;
get<Service>(runtimeIdentifier: string): Service;
}
export interface IKernelModule extends Function {
(kernel: IKernel): void;
}
export enum BindingScope {
Transient = 0,
Singleton = 1,
}
interface IKernelOptions {
middleware?: IMiddleware[];
modules?: IKernelModule[];
}
export class Binding<TServiceType> implements BindingInterface<TServiceType> {
public runtimeIdentifier: string;
public implementationType: {
new (): TServiceType;
};
public cache: TServiceType;
public scope: BindingScope;
constructor(runtimeIdentifier: string, implementationType: {
new (...args: any[]): TServiceType;
}, scopeType?: BindingScope);
}
export interface IKernelConstructor {
new(options?: IKernelOptions): IKernel;
}
export class Kernel implements KernelInterface {
public bind(typeBinding: BindingInterface<any>): void;
public unbind(runtimeIdentifier: string): void;
public unbindAll(): void;
public get<Service>(runtimeIdentifier: string): Service;
constructor();
}
export interface IKernel {
bind<T>(runtimeIdentifier: string): IBindingToSyntax<T>;
unbind(runtimeIdentifier: string): void;
unbindAll(): void;
get<Service>(runtimeIdentifier: string): Service;
getAll<Service>(runtimeIdentifier: string): Service[];
}
export function Inject(...typeIdentifiers: string[]): (typeConstructor: any) => void;
interface IBindingWhenSyntax<T> {
when(constraint: Constraint): void;
}
interface IBindingToSyntax<T> {
to(constructor: { new(...args: any[]): T; }): IBindingInSyntax<T>;
toValue(value: T): IBindingWhenSyntax<T>;
toConstructor(constructor: { new(...args: any[]): T; }): IBindingWhenSyntax<T>;
toFactory(factory: (context) => T): IBindingWhenSyntax<T>;
}
interface IBindingInSyntax<T> {
inTransientScope(): IBindingWhenSyntax<T>;
inSingletonScope(): IBindingWhenSyntax<T>;
}
export interface IBinding<T> {
runtimeIdentifier: string;
implementationType: { new(): T; };
factory: (context) => T;
cache: T;
scope: number; // BindingScope
type: number; // BindingType
}
export interface IContext {
/// Gets the kernel that is driving the activation.
kernel: IKernel;
/// Gets or sets the activation plan.
plan: IPlan;
addPlan(plan: IPlan);
}
export interface IMetadata {
key: string;
value: any;
}
export interface IPlan {
parentContext: IContext;
rootRequest: IRequest;
}
export interface ITarget {
service: IQueryableString;
name: IQueryableString;
metadata: Array<IMetadata>;
isArray(): boolean;
isNamed(): boolean;
isTagged(): boolean;
matchesName(name: string): boolean;
matchesTag(name: IMetadata): boolean;
}
export interface IQueryableString {
startsWith(searchString: string): boolean;
endsWith(searchString: string): boolean;
contains(searchString: string): boolean;
equals(compareString: string): boolean;
value(): string;
}
export interface IRequest {
/// The service that was requested.
service: string;
/// The parent context.
parentContext: IContext;
/// The parent request.
parentRequest: IRequest;
// The child requests
childRequests: IRequest[];
/// Gets the target that will receive the injection, if any.
target: ITarget;
/// Gets the stack of bindings which have been activated by this request.
bindings: IBinding<any>[];
// Adds a child request to the request
addChildRequest(
service: string,
bindings: (IBinding<any>|IBinding<any>[]),
target: ITarget): IRequest;
}
export type Constraint = (request: IRequest) => boolean;
export var Kernel: IKernelConstructor;
export function Inject(...typeIdentifiers: string[]): (typeConstructor: any) => void;
}

@@ -51,0 +131,0 @@

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc