Skip to content

Inject Decorator

This file provides the @Inject decorator for dependency injection in the @sodacore/di package. It allows properties in a class to be automatically resolved from the Registry by type or by a specified name.


Usage

typescript
import Inject from './inject';

class MyService {
  @Inject() public queue: QueueService;
  @Inject('CustomService') public custom: CustomService;
}
  • If no name is provided, the class type name is used to resolve the dependency from the Registry.
  • You can inject any value from the Registry, including non-class data, by specifying the name.

API

Inject(name?: string): PropertyDecorator

  • Parameters:
    • name (optional): The name to resolve from the Registry. If omitted, the property type's class name is used.
  • Returns: A property decorator.

How It Works

  • Sets metadata on the target property to mark it as injected.
  • Determines the injection key using the provided name or the property type's class name.
  • Defines a getter on the property that retrieves the value from the Registry when accessed.

Notes

  • Throws an error if the injection key cannot be determined.
  • The decorator is compatible with both class-based and non-class-based values in the Registry.

Released under the Apache-2.0 License.