Git Product home page Git Product logo

inversify-binding-decorators's Introduction

inversify-binding-decorators

Join the chat at https://gitter.im/inversify/InversifyJS Build Status Test Coverage npm version Dependencies img img Known Vulnerabilities

NPM NPM

An utility that allows developers to declare InversifyJS bindings using ES2016 decorators:

Installation

You can install inversify-binding-decorators using npm:

$ npm install inversify inversify-binding-decorators reflect-metadata --save

The inversify-binding-decorators type definitions are included in the npm module and require TypeScript 2.0. Please refer to the InversifyJS documentation to learn more about the installation process.

The basics

The InversifyJS API allows us to declare bindings using a fluent API:

import { injectable, Container } from "inversify";
import "reflect-metadata";

@injectable()
class Katana implements Weapon {
    public hit() {
        return "cut!";
    }
}

@injectable()
class Shuriken implements ThrowableWeapon {
    public throw() {
        return "hit!";
    }
}

var container = new Container();
container.bind<Katana>("Katana").to(Katana);
container.bind<Shuriken>("Shuriken").to(Shuriken);

This small utility allows you to declare bindings using decorators:

import { injectable, Container } from "inversify";
import { provide, buildProviderModule } from "inversify-binding-decorators";
import "reflect-metadata";

@provide(Katana)
class Katana implements Weapon {
    public hit() {
        return "cut!";
    }
}

@provide(Shuriken)
class Shuriken implements ThrowableWeapon {
    public throw() {
        return "hit!";
    }
}

var container = new Container();
// Reflects all decorators provided by this package and packages them into 
// a module to be loaded by the container
container.load(buildProviderModule());

Using @provide multiple times

If you try to apply @provide multiple times:

@provide("Ninja")
@provide("SilentNinja")
class Ninja {
    // ...
}

The library will throw an exception:

Cannot apply @injectable decorator multiple times. Please use @provide(ID, true) if you are trying to declare multiple bindings!

We throw an exception to ensure that you are are not trying to apply @provide multiple times by mistake.

You can overcome this by passing the force argument to @provide:

@provide("Ninja", true)
@provide("SilentNinja", true)
class Ninja {
    // ...
}

Using classes, string literals & symbols as identifiers

When you invoke @provide using classes:

@provide(Katana)
class Katana {
    public hit() {
        return "cut!";
    }
}

@provide(Ninja)
class Ninja {
    private _katana: Weapon;
    public constructor(
        katana: Weapon
    ) {
        this._katana = katana;
    }
    public fight() { return this._katana.hit(); };
}

A new binding is created under the hood:

container.bind<Katana>(Katana).to(Katana);
container.bind<Ninja>(Ninja).to(Ninja);

These bindings use classes as identidiers but you can also use string literals as identifiers:

let TYPE = {
    IKatana: "Katana",
    INinja: "Ninja"
};

@provide(TYPE.Katana)
class Katana implements Weapon {
    public hit() {
        return "cut!";
    }
}

@provide(TYPE.Ninja)
class Ninja implements Ninja {

    private _katana: Weapon;

    public constructor(
        @inject(TYPE.Katana) katana: Weapon
    ) {
        this._katana = katana;
    }

    public fight() { return this._katana.hit(); };

}

You can also use symbols as identifiers:

let TYPE = {
    Katana: Symbol("Katana"),
    Ninja: Symbol("Ninja")
};

@provide(TYPE.Katana)
class Katana implements Weapon {
    public hit() {
        return "cut!";
    }
}

@provide(TYPE.Ninja)
class Ninja implements Ninja {

    private _katana: Weapon;

    public constructor(
        @inject(TYPE.Katana) katana: Weapon
    ) {
        this._katana = katana;
    }

    public fight() { return this._katana.hit(); };

}

Fluent binding decorator

The basic @provide decorator doesn't allow you to declare contextual constraints, scope and other advanced binding features. However, inversify-binding-decorators includes a second decorator that allows you to achieve access the full potential of the fluent binding syntax:

import { injectable, Container } from "inversify";
import { fluentProvide, buildProviderModule } from "inversify-binding-decorators";

let TYPE = {
    Weapon : "Weapon",
    Ninja: "Ninja"
};

@fluentProvide(TYPE.Weapon).whenTargetTagged("throwable", true).done();
class Katana implements Weapon {
    public hit() {
        return "cut!";
    }
}

@fluentProvide(TYPE.Weapon).whenTargetTagged("throwable", false).done();
class Shuriken implements Weapon {
    public hit() {
        return "hit!";
    }
}

@fluentProvide(TYPE.Ninja).done();
class Ninja implements Ninja {

    private _katana: Weapon;
    private _shuriken: Weapon;

    public constructor(
        @inject(TYPE.Weapon) @tagged("throwable", false) katana: Weapon,
        @inject(TYPE.Weapon) @tagged("throwable", true) shuriken: ThrowableWeapon
    ) {
        this._katana = katana;
        this._shuriken = shuriken;
    }

    public fight() { return this._katana.hit(); };
    public sneak() { return this._shuriken.throw(); };

}

var container = new Container();
container.load(buildProviderModule());

One of the best things about the fluent decorator is that you can create aliases to fit your needs:

let provideThrowable = function(identifier, isThrowable) {
	return provide(identifier)
		      .whenTargetTagged("throwable", isThrowable)
		      .done();
};

@provideThrowable(TYPE.Weapon, true)
class Katana implements Weapon {
    public hit() {
        return "cut!";
    }
}

@provideThrowable(TYPE.Weapon, false)
class Shuriken implements Weapon {
    public hit() {
        return "hit!";
    }
}

Another example:

const provideSingleton = (identifier: any) => {
    return fluentProvide(identifier)
        .inSingletonScope()
        .done();
};

@provideSingleton(TYPE.Weapon)
class Shuriken implements Weapon {
    public hit() {
        return "hit!";
    }
}

Using @fluentProvide multiple times

If you try to apply @fluentProvide multiple times:

let container = new Container();

const provideSingleton = (identifier: any) => {
    return fluentProvide(identifier)
        .inSingletonScope()
        .done();
};

function shouldThrow() {
    @provideSingleton("Ninja")
    @provideSingleton("SilentNinja")
    class Ninja {}
    return Ninja;
}

The library will throw an exception:

Cannot apply @fluentProvide decorator multiple times but is has been used multiple times in Ninja Please use done(true) if you are trying to declare multiple bindings!

We throw an exception to ensure that you are are not trying to apply @fluentProvide multiple times by mistake.

You can overcome this by passing the force argument to done():

const provideSingleton = (identifier: any) => {
    return fluentProvide(identifier)
    .inSingletonScope()
    .done(true); // IMPORTANT!
};

function shouldThrow() {
    @provideSingleton("Ninja")
    @provideSingleton("SilentNinja")
    class Ninja {}
    return Ninja;
}
let container = new Container();
container.load(buildProviderModule());

The auto provide utility

This library includes a small utility apply to add the default @provide decorator to all the public properties of a module:

Consider the following example:

import * as entities from "../entities";

let container = new Container();
autoProvide(container, entities);
let warrior = container.get(entities.Warrior);
expect(warrior.fight()).eql("Using Katana...");

The contents of the entities.ts file are the following:

export { default as Warrior } from "./warrior";
export { default as Katana } from "./katana";

The contents of the katana.ts file are the following:

class Katana {
    public use() {
        return "Using Katana...";
    }
}

export default Katana;

The contents of the warrior.ts file are the following:

import Katana from "./katana";
import { inject } from "inversify";

class Warrior {
    private _weapon: Weapon;
    public constructor(
        // we need to declare binding because auto-provide uses
        // @injectable decorator at runtime not compilation time
        // in the future maybe this limitation will disappear
        // thanks to design-time decorators or some other TS feature
        @inject(Katana) weapon: Weapon
    ) {
        this._weapon = weapon;
    }
    public fight() {
        return this._weapon.use();
    }
}

export default Warrior;

Support

If you are experience any kind of issues we will be happy to help. You can report an issue using the issues page or the chat. You can also ask questions at Stack overflow using the inversifyjs tag.

If you want to share your thoughts with the development team or join us you will be able to do so using the official the mailing list. You can check out the wiki and browse the documented source code to learn more about InversifyJS internals.

Acknowledgements

Thanks a lot to all the contributors, all the developers out there using InversifyJS and all those that help us to spread the word by sharing content about InversifyJS online. Without your feedback and support this project would not be possible.

License

License under the MIT License (MIT)

Copyright Β© 2016 Remo H. Jansen

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

inversify-binding-decorators's People

Contributors

bwheel181 avatar dcavanagh avatar greenkeeper[bot] avatar greenkeeperio-bot avatar healgaren avatar kbirger avatar kyroath avatar leonardssh avatar lholznagel avatar podarudragos avatar remojansen avatar sidharthv96 avatar tantalon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

inversify-binding-decorators's Issues

Add multiple bindings...

Is there anyway to bind multiple decorators to a class? Also, would bindings be singleton providers or instances?

Usage with ESLint

When you're using a class as the type, you get the error: @typescript-eslint/no-use-before-define.

I'd rather not disable this line. Any chance to make @provide() without any arguments passed in default to the class type?

An in-range update of tslint is breaking the build 🚨

Version 5.3.0 of tslint just got published.

Branch Build failing 🚨
Dependency tslint
Current Version 5.2.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As tslint is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

Release Notes v5.3.0

This change may require a change to tslint.json

πŸŽ‰ Notable features & enhancements

Thanks to our contributors!

  • Andy Hanson
  • Klaus Meinhardt
  • Martin Probst
  • Filipe Silva
  • walkerburgin
  • RenΓ© Scheibe
Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of tslint is breaking the build 🚨

Version 4.3.0 of tslint just got published.

Branch Build failing 🚨
Dependency tslint
Current Version 4.2.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As tslint is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details
Release Notes v4.3.0
  • Enabled additional rules in tslint:latest configuration (#1981)
  • [new-rule] space-before-function-paren (#1897)
  • [new-rule] typeof-compare (#1927)
  • [new-rule] import-spacing (#1935)
  • [new-rule] unified-signatures (#1944)
  • [new-fixer] object-literal-key-quotes (#1953)
  • [new-fixer] no-angle-bracket-type-assertion (#1979)
  • [bugfix] adjacent-overload-signature now handles static/computed function names (#1831)
  • [bugfix] file-header now handles files with only comments (#1913)
  • [bugfix] no-consecutive-blank-lines now allows blank lines in template strings (#1886)
  • [bugfix] object-literal-key-quotes no longer throws exception when using rest operator (#1916)
  • [bugfix] restrict-plus-operands no longer shows false positive in ternary operation (#1925)
  • [bugfix] prefer-for-of now handles nested for loops with reused iterator (#1926)
  • [bugfix] Exit gracefully when tsconfig.json passed as --project argument doens't have files (#1933)
  • [bugfix] object-literal-key-quotes now handles shorthand and spread properties (#1945)
  • [bugfix] arrow-parens Allow binding patterns ([x, y]) => ... and ({x, y}) => ... to have parens (#1958)
  • [bugfix] semicolon fixer now handles comma separator in interfaces and indicates failure when commas are using in interfaces (#1856)
  • [bugfix] only-arrow-functions option allow-named-functions now allows function declarations (#1961)
  • [bugfix] prefer-for-of no longer shows false positive when array is in parentheses (#1986)
  • [bugfix] prefer-const now works for TypeScript versions < 2.1.0 (#1989)
  • [enhancement] member-access narrow location of error (#1964)

Thanks to our contributors!

  • Andrii Dieiev
  • @andy-ms
  • Andy Hanson
  • Josh Goldberg
  • Klaus Meinhardt
  • Linda_pp
  • Mohsen Azimi
  • Victor Grigoriu
  • Yuichi Nukiyama
  • cameron-mcateer
Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

fluentProvide - example

Could you please provide a full fluentProvide example?
I have this kind of issue:

import { Container, decorate, inject, injectable, interfaces as inversifyInterfaces, named } from "inversify";
import { fluentProvide, buildProviderModule } from "inversify-binding-decorators";
import "reflect-metadata";

const container = new Container();
const provideFluent = fluentProvide(container);
....
export function ProvideAsSingleton(symbol: inversifyInterfaces.ServiceIdentifier<any>): any {
    return provideFluent(symbol).inSingletonScope().done(true);
}
container.load(buildProviderModule());

export { container };

The issue is at:

const provideFluent = fluentProvide(container);

the error is:

[ts]
Argument of type 'Container' is not assignable to parameter of type 'string | symbol | Newable<any> | Abstract<any>'.
  Type 'Container' is not assignable to type 'Abstract<any>'.
    Property 'prototype' is missing in type 'Container'.

How can I use fluent provider?
thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.