@loopback/docs
Version:
Documentation files rendered at [https://loopback.io](https://loopback.io)
105 lines (56 loc) • 2.24 kB
Markdown
---
lang: en
title: 'API docs: core.service'
keywords: LoopBack 4.0, LoopBack 4, Node.js, TypeScript, OpenAPI
sidebar: lb4_sidebar
editurl: https://github.com/loopbackio/loopback-next/tree/master/packages/core
permalink: /doc/en/lb4/apidocs.core.service.html
---
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) > [@loopback/core](./core.md) > [service](./core.service.md)
## service() function
`@service` injects a service instance that matches the class or interface.
**Signature:**
```typescript
export declare function service(serviceInterface?: ServiceInterface, metadata?: InjectionMetadata): (target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: number | TypedPropertyDescriptor<any> | undefined) => void;
```
## Parameters
<table><thead><tr><th>
Parameter
</th><th>
Type
</th><th>
Description
</th></tr></thead>
<tbody><tr><td markdown="1">
serviceInterface
</td><td markdown="1">
[ServiceInterface](./core.serviceinterface.md)
</td><td markdown="1">
_(Optional)_ Interface for the service. It can be in one of the following forms:
- A class, such as MyService - A string that identifies the interface, such as `'MyService'` - A symbol that identifies the interface, such as `Symbol('MyService')`
If not provided, the value is inferred from the design:type of the parameter or property
</td></tr>
<tr><td markdown="1">
metadata
</td><td markdown="1">
[InjectionMetadata](./context.injectionmetadata.md)
</td><td markdown="1">
_(Optional)_
</td></tr>
</tbody></table>
**Returns:**
(target: Object, member: string \| undefined, methodDescriptorOrParameterIndex?: number \| TypedPropertyDescriptor<any> \| undefined) => void
## Example
```ts
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');
```