Security News
Supply Chain Attack Detected in Solana's web3.js Library
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
Highly inspired by Autofac.NET
We have tried to accommodate all the best DI and IoC practices for JavaScript
var di = new Di;
2.1
Constructor
2.1.1
External definitions2.1.2
In-place meta information2.1.3
Other ways2.2
Properties2.3
Methods3
Consume
3.1
Initialize registered components3.2
Create inherited classes3.3
[Create function delegates](#33-create function delegates)1
RegistrationThe greates challenge for DI frameworks in JavaScript is to get the list of dependencies for a constructor, method, etc. JavaScript is not statically typed, so here other ways should be found to declare the dependencies. And we also try to follow the 1st rule of any di framework -
"Your classes should not be dependent on the DI itself"
.
Though you can use it as a Service Locator
When registering the component, we specify identifiers, by which the dependency is resolved. It can be some another Type
, string identifier, self-type
. But we do not encourage you to use string identifiers.
It is also possible to get the instance without having previously to register the Type
const foo = di.resolve(Foo);
Later you can register another Type for this one.
1.1
TypeA Type
in JavaScript we call a Class
or a Function
, as almost any function
can be used as a contructor for an instance.
class Foo {
constructor (bar, qux) {}
}
// ----
di
.registerType(Foo)
.using(IBar, IQux)
.as(IFoo)
.as('foo')
.asSelf()
.onActivated(foo => console.log(foo));
1.2
InstancePass already instantiated class to the container, and it will be used by all dependents
di.registerInstance(new Foo(di.resolve(IBar), di.resolve(IQux))).as(IFoo);
// or use Initializer wich will be called on first `IFoo` require.
di.registerInstance(IBar, IFoo, (bar, foo) => new Foo(bar, foo)).as(IFoo);
// you can even suppress the lamda here
di.registerInstance(IBar, IFoo, Foo).as(IFoo);
1.3
FactoryRegister a function
which will create the instance on demand. Is similar to instance initializer, but the factory is called every time the dependency is required.
di.registerFactory(IBar, (bar) => {}).as(IFoo);
// No arguments are defined - we pass the di itself, for the case your factory method is out of the current di scope.
di.registerFactory(di => {}).as(IFoo);
2
Dependency defintions2.1
ConstructorUnder Constructor
also plain Functions are meant.
2.1.1
External definitionsFrom the previous paragraph you have already seen using
method, when registering the Type
. Here we say the di library what identifiers should be used to instantiate the arguments.
:sparkles: Pros: Your implementation is fully decoupled from the DI and the registration iteself.
class Foo {
constructor (logger) { logger.log() }
}
// ----
class Bar {
log (...args) { console.log(...args) }
}
// ---
class ILog { log () {} }
// ---
di
.registerType(Bar)
.as(ILog);
di
.registerType(Foo)
.using(ILog)
.asSelf();
2.1.2
In-place meta information:sparkles: Pros: Your implementation is decoupled from the DI, but holds meta information for the DI library.
Per default we read the static $inject
property on the Type
class Foo {
constructor (logger) { logger.log() }
}
Foo.$constructor = [ILog];
// ----
di
.registerType(Foo)
.asSelf();
You can override the reader and provide us with the Identifiers for injection.
var CustomMetaReader = {
getConstructor (Type) {
return Type.$inject;
}
};
di.defineMetaReader(CustomMetaReader);
// ----
class Foo {
constructor (logger) { logger.log() }
}
Foo.$inject = [ILog];
2.1.3
Other waysUnder the considiration are some other ways, like decorators from ES7, but it makes then your class
implementation to depend on di
library and its decorator.
:bulb: Do you have any ideas? Please share them via issues.
TypeScript: initially, this project targets plain JavaScript, but TypeScript support will be also implemented.
2.2
PropertiesProperty injections are supported by Type
s components.
2.2.1
External definitionsclass Foo {
constructor () {
this.logger = new DummyLogger();
}
doSmth () {
this.logger.log();
}
}
// ---
di
.registerType(Foo)
.properties({
// DummyLogger will be replaced with the registration for ILog
logger: ILog
})
.asSelf();
2.2.2
In-place meta informationPer default we read the static $properties
to get the key: Identifier
information.
class Foo {
constructor () { }
}
Foo.$properties = {
logger: ILog
};
// ----
di
.registerType(Foo)
.asSelf();
You can override the reader and provide us with the Identifiers for injection.
var CustomMetaReader = {
getProperties (Type) {
// return hash with {key: Identifier}
}
};
di.defineMetaReader(CustomMetaReader);
2.2.3
Other ways:bulb: Ideas about better API - please share!
2.3
MethodsInjections into Type
_s_functions.
2.3.1
External definitionsclass Foo {
doSmth (logger) {
logger.log();
}
}
// ---
di
.registerType(Foo)
.methods({
// The method on an instance can be the called without any arguments
// Di will provide required dependencies to the inner function
doSmth: [ILog]
})
.asSelf();
2.3.2
In-place meta informationPer default we read the static $methods
with key:[Identifier, ...]
information.
class Foo {
doSmth (logger) { logger.log() }
}
Foo.$methods = {
doSmth: [ILog]
};
// ----
di
.registerType(Foo)
.asSelf();
You can override the reader and provide us with the Identifiers for injection.
var CustomMetaReader = {
getMethods (Type) {
// return hash with {key: [Identifier, ...]}
}
};
di.defineMetaReader(CustomMetaReader);
2.3.3
Other ways:bulb: Ideas about better API - please share!
3
Consume3.1
Initialize registered componentsWe inject all dependencies and return ready to use component.
var x = di.resolve(IFoo);
3.2
Create inherited classesThe inherited class accepts empty constructor, in this case we will pass the resolved components to the base class.
var FooWrapper = di.wrapType(IFoo);
var foo = new FooWrapper();
3.3
Create function delegatesDefine function argument identifiers, and you can call the function without arguments.
var myFunction = di.wrapFunction(IFoo, IBar, (foo, bar) => {});
myFunction();
4
Additional configuration4.1
Predefine parameter valuesSometimes it is needed to set values for parameters, which will be directly passed inside the function.
class Foo {
constructor (bar, shouldDoSmth)
}
di
.registerType(Foo)
.using(Bar)
.withParams(null, true)
:one: Passing null values says the di library to resolve values from container by declared Type
:two: Boolean
true
from sample just shows the idea of passing values. You may want to get the value from app configuration or some other source.
4.2
Configurate argumentsArguments or values for a constructor/function are resolved from 3 sources:
With options "ignore" "extend" "override"
you can control how we handle the third source. Default is "override"
:checkered_flag:
:copyright: MIT - 2017 Atma.js Project
FAQs
Dependency injection library for Javascript/Typescript
We found that a-di demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.