- Notifications
You must be signed in to change notification settings - Fork0
atmajs/a-di
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Highly inspired byAutofac.NET
We have tried to accommodate all the best DI and IoC practices for JavaScript
const di = new Di;
2.1
Constructor2.1.1
External definitions2.1.2
Decorators2.1.3
Default parameters2.1.4
In-place meta information2.1.5
Other ways
2.2
Properties2.3
Methods
The greatest 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 the1st rule of any di framework -
"Your classes should not be dependent on the DI itself"
.
Though you can use it as aService Locator
When registering the component, you specify identifiers, by which the dependency is resolved. It can be some anotherType
, string identifier.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
constfoo=di.resolve(Foo);
Later you can register another Type for this one.
Class
constructor;
classFoo{constructor(bar,qux){}}
Pass already instantiated class to the container, and it will be used by all dependents
di.registerInstance(newFoo(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)=>newFoo(bar,foo)).as(IFoo);// you can even suppress the lamda heredi.registerInstance(IBar,IFoo,Foo).as(IFoo);
Register afunction
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);
From the previous paragraph you have already seenusing
method, when registering theType
. Here we define what identifiers should be used to instantiate the instance.
✨Pros: Your implementation is fully decoupled from the DI and the registration itself.
classFoo{constructor(logger){logger.log()}}// ----classBar{log(...args){console.log(...args)}}// ---classILog{log(){}}// ---di.registerType(Bar).as(ILog);di.registerType(Foo).using(ILog).asSelf().onActivated(foo=>console.log(foo));
✨Pros: In-place configuration, but has reference to the di instance
classFoo{constructor(@di.inject(ILog)logger){logger.log()}}
✨Pros:
new Foo()
also works
classFoo{constructor(logger=di.resolve(ILog)){logger.log()}}
Maybe most irrelevant feature, but anyway
✨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 theType
classFoo{static$constructor=[ILog]constructor(logger){logger.log()}}
You can override the reader and provide us with the Identifiers for injection.
constCustomMetaReader={getConstructor(Type){returnType.$inject;}};di.defineMetaReader(CustomMetaReader);// ----classFoo{static$inject=[ILog]constructor(logger){logger.log()}}
💬 Do you have any ideas? Please share them via issues.
TypeScript: initially, this project targets plain JavaScript, but TypeScript is preferred.
Property injections are supported byType
s components.
classFoo{constructor(){this.logger=newDummyLogger();}doSmth(){this.logger.log();}}// ---di.registerType(Foo).properties({// DummyLogger will be replaced with the registration for ILoglogger:ILog}).asSelf();
Per default we read the static$properties
to get thekey: Identifier
information.
classFoo{constructor(){}}Foo.$properties={logger:ILog};// ----di.registerType(Foo).asSelf();
You can override the reader and provide us with the Identifiers for injection.
letCustomMetaReader={getProperties(Type){// return hash with {key: Identifier}}};di.defineMetaReader(CustomMetaReader);
💬 Ideas about better API - please share!
Injections intoType
_s_functions.
classFoo{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 functiondoSmth:[ILog]}).asSelf();
Per default we read the static$methods
withkey:[Identifier, ...]
information.
classFoo{doSmth(logger){logger.log()}static$methods={doSmth:[ILog]};}// ----di.registerType(Foo).asSelf();
You can override the reader and provide us with the Identifiers for injection.
constCustomMetaReader={getMethods(Type){// return hash with {key: [Identifier, ...]}}};di.defineMetaReader(CustomMetaReader);
💬 Ideas about better API - please share!
We inject all dependencies and return ready to use component.
letx=di.resolve(IFoo);
The inherited class accepts empty constructor, in this case we will pass the resolved components to the base class.
letFooWrapper=di.wrapType(IFoo);letfoo=newFooWrapper();
Define function argument identifiers, and you can call the function without arguments.
letmyFunction=di.wrapFunction(IFoo,IBar,(foo,bar)=>{});myFunction();
Sometimes it is needed to set values for parameters, which will be directly passed inside the function.
classFoo{constructor(bar,shouldDoSmth)}di.registerType(Foo).using(Bar).withParams(null,true)
1️⃣ Passing null values says the di library to resolve values from container by declared Type
2️⃣ 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.
Argumentsor values for a constructor/function are resolved from 3 sources:
- Declared parameter values
- Type definitions
- Direct values from the current function call.
With options"ignore" "extend" "override"
you can control how we handle the third source. Default is"override"
We rarely use all of those registration and configuration features.
- All the
Services
,Workers
,Handlers
,Factories
- actually everything exceptData Models
- we use mostly as singletons. Means any initialization of an Instance we do viadi.resolve
. Note, that no configuration or registration is required - when nothing specified di initializes the class as-is.
We do this, while a class can
memoize
initialization, data, configuration, or method calls.
import{UserService}from'./UserService'// ....letservice=di.resolve(UserService);
- To have more clear dependency tree structure, we define some dependencies via constructor as default parameters:
import{UserService}from'./UserService'// ....classFoo{constructor(privateservice=di.resolve(UserService))}
- For multiple implementations we use abstract classes.
abstractclassAFoo{abstractlog()// ... some common logic}// Option 1. Register the implementation as a default for the base (AFoo)@di.for(AFoo)classSomeFooextendsAFoo(){}// Option 2. Without the decorator, the type could be registered later somewhere in code:di.registerType(AFoo).for(AFoo)//# Usage 1classUserService{constructor(foo=di.resolve(AFoo)){}}//# Usage 2classUserService{constructor( @di.inject(AFoo)foo:AFoo){}}
🏁
©️ MIT — 2021 Atma.js Project