Page Contents
Home > @loopback/core > service
service() function
@service
injects a service instance that matches the class or interface.
Signature:
export declare function service(serviceInterface?: ServiceInterface, metadata?: InjectionMetadata): (target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: number | TypedPropertyDescriptor<any> | undefined) => void;
Parameters
Parameter | Type | Description |
---|---|---|
serviceInterface | ServiceInterface | <p>(Optional) Interface for the service. It can be in one of the following forms:</p><p>- A class, such as MyService - A string that identifies the interface, such as 'MyService' - A symbol that identifies the interface, such as Symbol('MyService') </p><p>If not provided, the value is inferred from the design:type of the parameter or property</p> |
metadata | InjectionMetadata | (Optional) |
Returns:
(target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: number | TypedPropertyDescriptor<any> | undefined) => void
Example
const ctx = new Context();
ctx.bind('my-service').toClass(MyService);
ctx.bind('logger').toClass(Logger);
export class MyController {
constructor(@service(MyService) private myService: MyService) {}
@service()
private logger: Logger;
}
ctx.bind('my-controller').toClass(MyController);
await myController = ctx.get<MyController>('my-controller');