Skip to content

Commit

Permalink
docs: add init service factory
Browse files Browse the repository at this point in the history
(cherry picked from commit 8043e6e)
  • Loading branch information
czy88840616 committed Dec 24, 2024
1 parent 9da29c0 commit cd3d801
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
23 changes: 22 additions & 1 deletion site/docs/service_factory.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
`ServiceFactory` 是个抽象类,每个需要实现的服务,都需要继承他。


我们以一个 http 客户端为例,需要准备一个创建 http 客户端实例的方法,其中包含两个部分
我们以一个 http 客户端为例,需要准备一个创建 http 客户端实例的方法,其中包含几个部分


- 1、创建客户端实例的方法
- 2、客户端的配置
- 3、实例化服务类

```typescript
// 创建客户端的配置
Expand Down Expand Up @@ -114,6 +115,26 @@ export class HTTPClientServiceFactory extends ServiceFactory<HTTPClient> {
`initClients` 方法是基类中实现的,它需要传递一个完整的用户配置,并循环调用 `createClient` 来创建对象,保存到内存中。


### 3、实例化服务类

为了方便用户使用,我们还需要提前将服务类创建,一般来说,只需要在组件或者项目的生命周期中实例化即可。

```typescript
import { Configuration } from '@midwayjs/core';

@Configuration({
imports: [
// ...
]
})
export class ContainerConfiguration {
async onReady(container) {
// 实例化服务类
await container.getAsync(HTTPClientServiceFactory);
}
}
```


## 获取实例

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ for example, our oss component creates multiple oss objects, so you need to leav
`ServiceFactory` is an abstract class, and every service that needs to be implemented needs to be inherited.


Take an http client as an example, we need to prepare a method to create an http client instance, which contains two parts:
Take an http client as an example, we need to prepare a method to create an http client instance, which contains several parts:


- 1. Method for creating a client instance
- 2. Configuration of Client
- 3. Instantiate service class

```typescript
// Create client configuration
Expand Down Expand Up @@ -114,6 +115,27 @@ export class HTTPClientServiceFactory extends ServiceFactory<HTTPClient> {
`initClients` method is implemented in the base class. It needs to pass a complete user configuration and call the `createClient` in a loop to create the object and save it to memory.


### 3. Instantiate service class

To make it easier for users to use, we also need to create the service class in advance. Generally speaking, we only need to instantiate it in the lifecycle of components or projects.

```typescript
import { Configuration } from '@midwayjs/core';

@Configuration({
imports: [
// ...
]
})
export class ContainerConfiguration {
async onReady(container) {
// Instantiate service class
await container.getAsync(HTTPClientServiceFactory);
}
}
```


## Get instance


Expand Down

0 comments on commit cd3d801

Please sign in to comment.