@loopback/docs
Version:
Documentation for LoopBack 4
57 lines (36 loc) • 1.9 kB
Markdown
---
lang: en
title: 'API docs: core.service'
keywords: LoopBack 4.0, LoopBack 4
sidebar: lb4_sidebar
editurl: https://github.com/strongloop/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.
<b>Signature:</b>
```typescript
export declare function service(serviceInterface?: ServiceInterface, metadata?: InjectionMetadata): (target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: number | TypedPropertyDescriptor<any> | undefined) => void;
```
## Parameters
| Parameter | Type | Description |
| --- | --- | --- |
| serviceInterface | <code>ServiceInterface</code> | 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 <code>'MyService'</code> - A symbol that identifies the interface, such as <code>Symbol('MyService')</code>If not provided, the value is inferred from the design:type of the parameter or property |
| metadata | <code>InjectionMetadata</code> | |
<b>Returns:</b>
`(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');
```