@fun-coder/ioc
v0.2.5
Published
Inversion of control
Downloads
5
Readme
IOC Container
Define classes
import { Context, injected } from '@fun-coder/ioc';
abstract class BaseService {
abstract getName(): string;
}
class ServiceA extends BaseService {
getName(): string {
return 'Hello, I come from A';
};
}
class ServiceB extends BaseService {
@injected()
serviceA: ServiceA;
getName(): string {
return 'Hello, I come from B';
};
}
Create context
const context = Context.create(ServiceA, ServiceB);
Get instance from context
const serviceA = context.get(ServiceA);
serviceA.getName(); // Hello, I come from A;
const serviceB = context.get(ServiceB);
serviceB.getName(); // Hello, I come from B;
console.log(serviceB.serviceA === serviceA); // => true
Get instances by parent class
context.getAll(BaseService); // [serviceA, serviceB]