🌀
type-chef-di Docs
GitHub
  • 👋Welcome to type-chef-di documentation
  • Overview
    • ✨Getting started
  • Fundamentals
    • 🍎Container Options, extendability
    • 👨‍🍳Injection
      • 🍕Type injection
      • 🍪Token registration
      • ☕Token Injection
      • 🌮Mixed injection
    • 🛠️Decorators
      • ✅@Injectable({instantiation: "singleton" | "prototype"})
      • 🎯@Inject<T>(key: string | Type<T>)
      • 🍍@InjectProperty<T>(key: string | Type<T>)
      • 🍭@Setter()
      • 🔆@InitMethod()
      • 🏭@FactoryMethod()
      • ⚡@AddTags(tags)
      • 🪃@RunBefore(key: string | Type<IRunBefore>)
      • 🛴@RunAfter(key: string | Type<IRunAfter>)
      • 🌕@MethodWrapper(key: string | Type<IMethodWrapper>)
  • Use Cases
    • 🎨Plans
    • 🖥️For Developers
  • Other
    • 💡DI / IoC
Powered by GitBook
On this page
Edit on GitHub
  1. Fundamentals
  2. Injection

Token Injection

If you want more control over the injection process you can use the token injection. This lets you inject the value that you registered.

The di can't resolve automatically the primitive types, eg. string, number, interfaces... You must specify Token registration the value and use the @Inject decorator for that

class Service {

    constructor(@Inject("serviceStr") private readonly value: string) {
    }

    public say() {
        return `${this.value}`;
    }
}
class Client {

    constructor(
             @Inject("clientStr") private readonly value: string,
             @Inject("service") private readonly service: Service // or  @Inject<IService>(Service)
             ) {
    }

    public say() {
        return `I like ${this.value} and ${this.service.say()}`;
    }
}


async function run() {
    const container = new Container();
    container.register("clientStr", "coffee");
    container.register("serviceStr", "pizza");
    container.register("service", Service);
    container.register("client", Client);
    const service = await container.resolve<Client>("client"); // new Service('pizza');
    const service2 = await container.resolveByType<Client>(Client); // new Client('coffee', new Service('pizza'));
    console.log(service.say()); // client says: I like pizza and coffee
    console.log(service2.say()); // client says: I like pizza and coffee
}

run();
PreviousToken registrationNextMixed injection

Last updated 2 years ago

👨‍🍳
☕