Skip to content

@half0wl/container / Inject

Function: Inject()

ts
function Inject<T>(factory): (_target, propertyKey) => void;

Defined in: decorators.ts:91

Property decorator for declarative inter-service dependency injection.

Defines a lazy getter that resolves the dependency from the same container on first access and caches it per-instance. Uses a factory function (() => X instead of X directly) to avoid circular import issues between service files.

Requires experimentalDecorators: true in tsconfig.json.

Type Parameters

Type ParameterDescription
TThe injected service type

Parameters

ParameterTypeDescription
factory() => Constructor<T>A factory function returning the service class constructor. Called lazily on first property access.

Returns

A property decorator

ts
(_target, propertyKey): void;

Parameters

ParameterType
_targetobject
propertyKeystring | symbol

Returns

void

Example

ts
@Service()
class AuthService extends BaseService<ContainerDeps> {
  @Inject(() => UserService)
  declare readonly userService: UserService;

  @Inject(() => TokenService)
  declare readonly tokenService: TokenService;

  authenticate(token: string) {
    const payload = this.tokenService.verify(token);
    return this.userService.findById(payload.userId);
  }
}