How to use inversify - 10 common examples

To help you get started, we’ve selected a few inversify examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DefinitelyTyped / DefinitelyTyped / inversify / inversify-tests.ts View on Github external
kernel.unbind("INinja");
    kernel.unbindAll();

    // Kernel modules
    let module: IKernelModule = (k: IKernel) => {
        k.bind("INinja").to(Ninja);
        k.bind("IKatana").to(Katana).inTransientScope();
        k.bind("IShuriken").to(Shuriken).inSingletonScope();
    };

    let options: IKernelOptions = {
        middleware: [],
        modules: [module]
    };

    kernel = new Kernel(options);
    let ninja2 = kernel.get("INinja");
    console.log(ninja2);

    // binding types
    kernel.bind("IKatana").to(Katana);
    kernel.bind("IKatana").toValue(new Katana());

    kernel.bind>("IKatana").toConstructor(Katana);

    kernel.bind>("IKatana").toFactory((context) => {
        return () => {
            return kernel.get("IKatana");
        };
    });

    kernel.bind>("IKatana").toAutoFactory();
github DefinitelyTyped / DefinitelyTyped / inversify-inject-decorators / inversify-inject-decorators-tests.ts View on Github external
public secondaryWeapon: Weapon;

  }

  kernel.bind(TYPES.Weapon).to(Sword).whenTargetTagged("throwwable", false);
  kernel.bind(TYPES.Weapon).to(Shuriken).whenTargetTagged("throwwable", true);

  let warrior = new Warrior();
  console.log(warrior.primaryWeapon instanceof Sword); // true
  console.log(warrior.primaryWeapon instanceof Shuriken); // true

}

module lazyMultiInject {

  let kernel = new Kernel();
  let { lazyMultiInject } = getDecorators(kernel);
  let TYPES = { Weapon: "Weapon" };

  interface Weapon {
      name: string;
      durability: number;
      use(): void;
  }

  @injectable()
  class Sword implements Weapon {
      public name: string;
      public durability: number;
      public constructor() {
          this.durability = 100;
          this.name = "Sword";
github inversify / inversify-binding-decorators / type_definitions / inversify-binding-decorators / inversify-binding-decorators-tests.ts View on Github external
/// 

import { inject, Kernel } from "inversify";
import { autoProvide, makeProvideDecorator, makeFluentProvideDecorator } from "inversify-binding-decorators";

module decorator {
    let kernel = new Kernel();
    let provide = makeProvideDecorator(kernel);

    interface INinja {
        fight(): string;
        sneak(): string;
    }

    interface IKatana {
        hit(): string;
    }

    interface IShuriken {
        throw(): string;
    }

    let TYPE = {
github DefinitelyTyped / DefinitelyTyped / inversify-express-utils / inversify-express-utils-tests.ts View on Github external
/// 

import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method, TYPE } from "inversify-express-utils";
import * as express from "express";
import { Kernel } from "inversify";

let kernel = new Kernel();

module server {

    let server = new InversifyExpressServer(kernel);

    server
        .setConfig((app: express.Application) => {
            app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
                console.log("hello world");
                next();
            });
        })
        .setErrorConfig((app: express.Application) => {
            app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
                console.error(err.stack);
                res.status(500).send("Something broke!");
github JohnSimerlink / branches_front_end_private / inversify.config.ts View on Github external
bind(TYPES.MutableSubscribableGlobalStoreArgs)
		.to(MutableSubscribableGlobalStoreArgs);

	bind
	(TYPES.IMutableSubscribableGlobalStore)
		.to(MutableSubscribableGlobalStore)
		.inSingletonScope()
		.whenTargetIsDefault();



		// ^^ This will get overriden in the BranchesStore constructor
});
//
const rendering = new ContainerModule((bind: interfaces.Bind, unbind: interfaces.Unbind) => {
	bind(TYPES.radian).toConstantValue(0);
	bind(TYPES.fGetStore).toConstantValue(() => { return { commit(){}} as any as Store})

	const {
		CanvasUI,
		CanvasUIArgs
	} = require('./app/objects/sigmaNode/CanvasUI');
	bind(TYPES.CanvasUI).to(CanvasUI);
	bind(TYPES.CanvasUIArgs)
		.to(CanvasUIArgs);

	// TODO: fix these bindings for if we have multiple sigma instances.
	bind(TYPES.ISigmaNodes).toConstantValue({});
	bind(TYPES.ISigmaEdges).toConstantValue({});

	bind(TYPES.IContentUserData).toDynamicValue((context: interfaces.Context) => {
github eclipse-theia / theia / packages / cpp / src / browser / cpp-language-client-contribution.ts View on Github external
@inject(ILogger)
    protected readonly logger: ILogger;

    constructor(
        @inject(Workspace) protected readonly workspace: Workspace,
        @inject(Languages) protected readonly languages: Languages,
        @inject(LanguageClientFactory) protected readonly languageClientFactory: LanguageClientFactory,
        @inject(SemanticHighlightingService) protected readonly semanticHighlightingService: SemanticHighlightingService,
    ) {
        super(workspace, languages, languageClientFactory);
    }

    /**
     * Initialize the client contribution.
     */
    @postConstruct()
    protected init(): void {
        this.cppBuildConfigurations.onActiveConfigChange2(() => this.onActiveBuildConfigChanged());
        this.cppPreferences.onPreferenceChanged(() => this.restart());
    }

    /**
     * Handle the language client `onReady` event.
     * @param languageClient the language client.
     */
    protected onReady(languageClient: ILanguageClient): void {
        super.onReady(languageClient);

        // Display the C/C++ build configurations status bar element to select active build config
        this.cppBuildConfigurationsStatusBarElement.show();
    }
github eclipse / sprotty / src / base / views / viewer-cache.ts View on Github external
import { SModelRoot } from "../model/smodel";
import { TYPES } from "../types";
import { Action } from "../actions/action";
import { AnimationFrameSyncer } from "../animations/animation-frame-syncer";
import { IViewer } from "./viewer";

/**
 * Updating the view is rather expensive, and it doesn't make sense to calculate
 * more then one update per animation (rendering) frame. So this class batches
 * all incoming model changes and only renders the last one when the next animation
 * frame comes.
 */
@injectable()
export class ViewerCache implements IViewer {

    @inject(TYPES.IViewer) protected delegate: IViewer;
    @inject(TYPES.AnimationFrameSyncer) protected syncer: AnimationFrameSyncer;

    protected cachedModel?: SModelRoot;

    update(model: SModelRoot, cause?: Action): void {
        if (cause !== undefined) {
            // Forward the update immediately in order to pass the cause action
            this.delegate.update(model, cause);
            this.cachedModel = undefined;
        } else {
            const isCacheEmpty = this.cachedModel === undefined;
            this.cachedModel = model;
            if (isCacheEmpty) {
                this.scheduleUpdate();
            }
        }
github DonJayamanne / pythonVSCode / src / client / datascience / jupyter / jupyterSessionManagerFactory.ts View on Github external
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import { inject, injectable } from 'inversify';

import { IConfigurationService } from '../../common/types';
import { IConnection, IJupyterPasswordConnect, IJupyterSessionManager, IJupyterSessionManagerFactory } from '../types';
import { JupyterSessionManager } from './jupyterSessionManager';
import { KernelSelector } from './kernels/kernelSelector';

@injectable()
export class JupyterSessionManagerFactory implements IJupyterSessionManagerFactory {

    constructor(
        @inject(IJupyterPasswordConnect) private jupyterPasswordConnect: IJupyterPasswordConnect,
        @inject(IConfigurationService) private config: IConfigurationService,
        @inject(KernelSelector) private kernelSelector: KernelSelector
    ) {
    }

    /**
     * Creates a new IJupyterSessionManager.
     * @param connInfo - connection information to the server that's already running.
     * @param failOnPassword - whether or not to fail the creation if a password is required.
     */
    public async create(connInfo: IConnection, failOnPassword?: boolean): Promise {
        const result = new JupyterSessionManager(this.jupyterPasswordConnect, this.config, failOnPassword, this.kernelSelector);
github JohnSimerlink / branches_front_end_private / app / objects / Subscribable.ts View on Github external
// tslint:disable max-classes-per-file
import {inject, injectable} from 'inversify';
import {ISubscribable, updatesCallback} from './ISubscribable';
import {IDatedMutation} from './mutations/IMutation';
import {SetMutationTypes} from './set/SetMutationTypes';
import {TYPES} from './types';

@injectable()
    // TODO: make abstract?
class Subscribable implements ISubscribable {
    protected updates: {val?: object} = {}
    protected pushes: {mutations?: IDatedMutation} = {}
    private updatesCallbacks: updatesCallback[];
    constructor(@inject(TYPES.SubscribableArgs){updatesCallbacks = []} = {updatesCallbacks: []}) {
        this.updatesCallbacks = updatesCallbacks /* let updatesCallbacks be injected for
         1) modularity reasons
         2) if we want to cache the state of this entire object, we could load in the previous state
         of set, mutations, and updatesCallbacks easy-peasy
         */
    }
    public onUpdate(func: updatesCallback) {
        // throw new TypeError('func - ' + JSON.stringify(func))
        this.updatesCallbacks.push(func)
    }
github openplannerteam / planner.js / src / configs / basic_train.ts View on Github external
import CSAProfile from "../planner/public-transport/CSAProfile";
import IJourneyExtractor from "../planner/public-transport/IJourneyExtractor";
import IPublicTransportPlanner from "../planner/public-transport/IPublicTransportPlanner";
import JourneyExtractorProfile from "../planner/public-transport/JourneyExtractorProfile";
import IRoadPlanner from "../planner/road/IRoadPlanner";
import RoadPlannerPathfinding from "../planner/road/RoadPlannerPathfinding";
import IReachableStopsFinder from "../planner/stops/IReachableStopsFinder";
import ReachableStopsFinderDelaunay from "../planner/stops/ReachableStopsFinderDelaunay";
import ReachableStopsFinderOnlySelf from "../planner/stops/ReachableStopsFinderOnlySelf";
import QueryRunnerExponential from "../query-runner/exponential/QueryRunnerExponential";
import ILocationResolver from "../query-runner/ILocationResolver";
import IQueryRunner from "../query-runner/IQueryRunner";
import LocationResolverConvenience from "../query-runner/LocationResolverConvenience";
import TYPES from "../types";

const container = new Container();
container.bind(TYPES.Context).to(Context).inSingletonScope();
container.bind(TYPES.QueryRunner).to(QueryRunnerExponential);
container.bind(TYPES.LocationResolver).to(LocationResolverConvenience);

// TODO, make this a fixed property of the planner itself
container.bind(TYPES.JourneyExtractor)
  .to(JourneyExtractorProfile);

container.bind(TYPES.PublicTransportPlanner)
  .to(CSAProfile);
container.bind>(TYPES.PublicTransportPlannerFactory)
  .toAutoFactory(TYPES.PublicTransportPlanner);

container.bind(TYPES.RoadPlanner)
  .to(RoadPlannerPathfinding);