A simple service container
- Create some services:
interface Car {
getDriverName(): string;
}
class CarImpl implements Car {
constructor(private readonly driver: Driver) {}
getDriverName() {
return this.driver.getName();
}
}
interface Driver {
getName(): string;
}
class DriverImpl implements Driver {
getName() {
return "Michael Schumacher";
}
}
- Explain to Service Container how to create services, use factories for this:
class CarFactory implements ServiceFactory {
create(container: ServiceContainer): CarImpl {
const driver = container.get("driver");
return new CarImpl(driver);
}
}
- Create services Specification:
const spec = new Map();
spec.set("car", new CarFactory());
spec.set("driver", () => new DriverImpl());
If creating a service is trivial, as for driver
, we can simply pass a function as a factory.
As for class based factory we can pass ServiceContainer
as a function parameter.
- Create Service Container with this Specification:
const serviceContainer = new ServiceContainer(spec);
- Get some service and call its method:
const car: Car = serviceContainer.get("car");
console.log(car.getDriverName());
- Get string "Michael Schumacher".