【前端】IOC容器(v4)

什么是IOC容器?

IOC不是一种技术,只是一种思想,一个重要的面向对象编程的法则,它能指导我们如何设计出松耦合,更优良的程序。传统应用程序都是由我们在类内部主动创建依赖对象,从而导致类与类之间高耦合,难于测试;有了IOC容器后,把创建和查找依赖对象的控制权交给了容器,由容器进行注入组合对象,所以对象与对象之间是松散耦合,这样也方便测试,利于功能复用,更重要的使程序的整个体系结构变得非常灵活。在运行期,在外部容器动态的将依赖对象注入组件,当外部容器启动后,外部容器就会初始化。创建并管理对象实例,以及销毁,这种应用本身不负责依赖对象的创建和维护,依赖对象的创建和维护是由外部容器负责的称为控制反转

IOC(控制反转)和DI(依赖注入)

IOC(Inversion of Control, 控制反转):通过外部容器管理对象实例的一种思想。
DI(Dependency Injection, 依赖注入):IOC的一种实现方式。

作者简述

IOC是Spring框架(一种以Java为语言开发的框架)的核心,并贯穿始终。其面向接口的开发能力,使得服务调用方和服务提供方可以做到完全解耦,只要遵循接口定义的规则进行调用,具体服务的实现可以是多样化的。

对于前端,我们使用inversify进行了IOC的实现。其强大的解耦能力可以使得平台进行大量的抽象,而无需关系具体的实现。

接下来,我们将介绍IOC在开发中的基本运用。

API

为了方便起见,我们将IOC相关功能与组件SPI的调用方式放在了一起。(更高版本的平台版本将自动获得该能力)

export class SPI {
  /**
   * register singleton service
   */
  public static Service;

  /**
   * autowired service property/parameter in service
   */
  public static Autowired;

  /**
   * service construct after execute method
   */
  public static PostConstruct;

  /**
   * autowired service in widget
   */
  public static Instantiate;

  /**
   * autowired services in widget
   */
  public static Instantiates;

  /**
   * service construct after execute method in widget
   */
  public static InstantiatePostConstruct;
}

创建第一个服务

service/ProductService.ts
import { ServiceIdentifier } from '@kunlun/dependencies';

/**
 * 产品
 */
export interface Product {
  id: string;
  name: string;
}

/**
 * 产品服务
 */
export interface ProductService {
  /**
   * 获取产品列表
   */
  getProducts(): Promise<Product[]>;

  /**
   * 通过ID获取产品
   * @param id 产品ID
   */
  getProductById(id: string): Promise<Product | undefined>;
}

/**
 * 产品服务Token
 */
export const ProductServiceToken = ServiceIdentifier<ProductService>('ProductService');
service/impl/ProductServiceImpl.ts
import { SPI } from '@kunlun/dependencies';
import { Product, ProductService, ProductServiceToken } from '../ProductService';

@SPI.Service(ProductServiceToken)
export class ProductServiceImpl implements ProductService {
  public async getProducts(): Promise<Product[]> {
    // request api get products
    return [];
  }

  public async getProductById(id: string): Promise<Product | undefined> {
    // request api get product by id
    return undefined;
  }
}
service/impl/index.ts
export * from './ProductServiceImpl';
service/index.ts
export * from './impl';
export * from './ProductService';

这样,我们便创建了一个ProductService服务,它定义了获取产品列表通过ID获取产品两个方法。接下来,我们要在可能需要的地方进行调用。

Class Component(ts)中使用ProductService服务

ProductListWidget.ts
import { BaseElementWidget, SPI, Widget } from '@kunlun/dependencies';
import { ProductService, ProductServiceToken } from '../service';
import ProductList from './ProductList.vue';

@SPI.ClassFactory(BaseElementWidget.Token({ widget: 'Product' }))
export class ProductListWidget extends BaseElementWidget {
  @SPI.Instantiate(ProductServiceToken)
  protected productService: ProductService | undefined;

  public initialize(props) {
    super.initialize(props);
    this.setComponent(ProductList);
    return this;
  }

  @Widget.Method()
  public loadProducts() {
    return this.productService?.getProducts();
  }

  @Widget.Method()
  public loadProduct(id: string) {
    return this.productService?.getProductById(id);
  }
}

在其他Service实现中使用ProductService服务

OtherServiceImpl.ts
import { SPI } from '@kunlun/dependencies';
import { OtherService, OtherServiceToken } from '../OtherService';
import { ProductService, ProductServiceToken } from '../ProductService';

@SPI.Service(OtherServiceToken)
export class OtherServiceImpl implements OtherService {
  @SPI.Autowired(ProductServiceToken)
  protected productService!: ProductService;

  public async do() {
    const products = await this.productService.getProducts();
    // do something
  }
}

值得一提的是,SPI.Autowired默认要求服务必须存在,否则会直接报错。如果其不是必须的,可以使用以下方式进行定义:

@SPI.Autowired(ProductServiceToken, { required: false })
protected productService: ProductService | undefined;

其他API的使用

SPI.PostConstruct

在实例初始化后执行,仅用于服务中,无法用于组件中。

@SPI.Service(OtherServiceToken)
export class OtherServiceImpl implements OtherService {
  @SPI.Autowired(ProductServiceToken)
  protected productService!: ProductService;

  @SPI.PostConstruct()
  public init() {
    console.log('post construct init.', this.productService);
  }
}
SPI.Instantiates

SPI.Instantiate类似,不过其声明的类型为服务数组,当没有任何服务时,将获得空数组,而不是空。因此可以使用以下方式进行定义:

@SPI.Instantiates(ProductServiceToken)
protected productServices!: ProductService[];
SPI.InstantiatePostConstruct

SPI.PostConstruct类似,不同之处在于,其仅用于组件中,无法用于服务中。虽然,我们提供了这种方式,但其实际应用场景相当有限,由于实例化组件时调用的方法为类的constructor方法,其init方法紧跟其后执行,此时,并没有执行任何组件初始化,Vue生命周期等逻辑,因此其对于业务组件来说并不是有意义的。

@SPI.ClassFactory(BaseElementWidget.Token({ widget: 'Product' }))
export class ProductListWidget extends BaseElementWidget {
  @SPI.Instantiate(ProductServiceToken)
  protected productService: ProductService | undefined;

  @SPI.InstantiatePostConstruct()
  protected init() {
    console.log('post construct init', this.productService);
  }
}
SPI.RawInstantiate

该方法并非装饰器,而是可以直接在代码中静态调用的方法。其为SPI.Instantiate的具体实现,可以在任何地方执行。

const productService = SPI.Instantiate(ProductServiceToken);
SPI.RawInstantiates

SPI.RawInstantiate类似,其为SPI.Instantiates的具体实现,可以在任何地方执行。

const productServices = SPI.Instantiates(ProductServiceToken);

注意事项

  • 在使用IOC时,我们并不希望Class Component(ts)组件也被注册成服务,因此,在该类上使用SPI.Service是无效的,甚至可能会带来其他意想不到的问题。
  • SPI.Autowired只能用于其他服务,而不能用于Class Component(ts)组件。
  • SPI.Instantiate只能用于Class Component(ts)组件,而不能用于其他服务。
  • 所有服务实例均为单例,且无法修改。未来可能会提供多例的实现功能,目前从设计角度上考虑不建议使用。

这样设计的目的在于,IOC容器的性能虽然在整体上没有太大的问题,不过为了避免不必要的查找,所以我们并没有通过IOC容器来创建组件。我们需要尽可能的将查找范围最小化。

Oinone社区 作者:nation原创文章,如若转载,请注明出处:https://doc.oinone.top/frontend/52.html

访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验

(0)
nation的头像nation数式员工
上一篇 2023年6月20日 pm4:07
下一篇 2023年11月2日 pm1:58

相关推荐

  • 在前端视图添加自定义的区域块

    添加自定义区域块 平台提供了一系列默认的视图布局,可以帮助开发人员快速构建出复杂的企业应用系统。当然,我们可以使用自定义区域块来扩展表格、表单、画廊、树形等视图。 自定义区域块概述 平台视图布局都是通过XML配置实现的。在视图布局中,我们可以使用一些特定的元素标签来构建视图的表头、表单、搜索区域等部分。而自定义区域块,就是这些元素标签之外的部分。我们可以通过在视图布局的XML中添加自定义区域块,来扩展页面功能。 视图类型及相关元素 视图类型分为表格(TABLE)、表单(FORM)、画廊(GALLERY)、树形(TREE)等。不同类型的视图布局,包含的元素也有所不同。 下面是几种视图类型及其对应的元素: 表格:搜索区域、表格主体,其中表格主体包含了表格上面的动作、表格区域等部分。 表单:表单区域,包含了表单动作、表单区域等部分。 画廊:动作、卡片详细信息。 在表格页面添加自定义区域块 以下是一个示例,演示如何在表格页面顶部添加自定义区域块。 1. 修改视图布局XML 首先,我们需要修改表格视图的XML布局,添加自定义区域块元素标签。 <view type="TABLE"> <!– 这是搜索区域 –> <pack widget="group"> <view type="SEARCH"> <element widget="search" slot="search" slotSupport="field" /> </view> </pack> <!– 这是表格主体 –> <pack widget="group" slot="tableGroup"> <!– 在这里添加自定义区域块元素标签 –> <element widget="MyCustomElement"></element> <!– 这是表格上面的动作 –> <element widget="actionBar" slot="actionBar" slotSupport="action"> <xslot name="actions" slotSupport="action" /> </element> <!– 这是表格区域 –> <element widget="table" slot="table" slotSupport="field"> <element widget="expandColumn" slot="expandRow" /> <xslot name="fields" slotSupport="field" /> <element widget="rowActions" slot="rowActions" slotSupport="action" /> </element> </pack> </view> 在上述代码中,我们添加了一个名为MyCustomElement的元素标签。这将作为我们自定义区域块的容器。 2. 创建自定义Vue组件 接下来,我们需要创建一个Vue组件,并将其指定为自定义元素标签MyCustomElement的模板。 <template> <div> <!– 在这里编写自定义区域块的内容 –> <p>Hello, world!</p> </div> </template> <script lang="ts"> import { defineComponent } from 'vue'; export default defineComponent({ components: { }, props: [], setup(props) { return {}; } }); </script> 在上述代码中,我们定义了一个非常简单的Vue组件,它在页面上显示一个“Hello, world!”的文本信息。 3. 创建自定义Element Widget 为了使自定义Vue组件与XML布局文件关联起来,我们需要创建一个对应的Element Widget。 import { BaseElementWidget, SPI, BaseElementViewWidget, Widget, ViewMode, FormWidget, BaseElementWidgetProps } from '@kunlun/dependencies'; import MyCustomElement from './MyCustomElement.vue'; @SPI.ClassFactory(BaseElementWidget.Token({ widget: 'MyCustomElementWidget' })) export class MyCustomElementWidget extends BaseElementWidget { public initialize(props: BaseElementWidgetProps): this { super.initialize(props) this.setComponent(MyCustomElement) return this } } 在上述代码中,我们继承了BaseElementWidget类,并在其中指定了Vue组件MyCustomElement。这样,XML布局文件中的元素标签就能够正确地与Vue组件关联起来。 4. 注册视图布局 最后,我们需要将上述代码配置注册。具体而言,我们需要调用registerLayout方法来将XML布局文件、模块名和视图类型进行关联。 import { registerLayout, ViewType } from '@kunlun/dependencies'; registerLayout( `<view type="TABLE"> <pack widget="group"> <view type="SEARCH"> <element widget="search" slot="search" slotSupport="field" />…

    2023年11月1日
    2.0K00
  • 如何自定义指定页面的样式

    可以通过在layout上给页面元素加css的class来解决此问题 import { registerLayout, ViewType } from '@kunlun/dependencies'; export const install = () => { registerLayout( ` <!– 给视图加class –> <view type="FORM" class="my-form-view"> <!– 给动作条组件加class –> <element widget="actionBar" slot="actionBar" class="my-action-bar" slotSupport="action" > <xslot name="actions" slotSupport="action" /> </element> <!– 给表单组件加class –> <element widget="form" slot="form" class="my-form-widget"> <xslot name="fields" slotSupport="pack,field" /> </element> </view> `, { viewType: ViewType.Form, // 页面的模型编码,可在浏览器地址栏的model=xxxx获取 model: 'resource.k2.Model0000000109', // 页面的动作名称,可在浏览器地址栏的action=xxxx获取 actionName: 'uiViewb2de116be1754ff781e1ffa8065477fa' } ); }; install(); 这样我们就可以在浏览器的html标签中查看到给组件加的class,通过加上这个作用域,可以给当前页面写特定样式

    2024年8月16日
    70600
  • 自定义的「视图、字段」调用界面设计器配置的按钮(包含权限控制)

    我们在业务开发中,经常会遇到自定义的视图或字段。有时候期望点击某一块区域的时候,打开一个弹窗或者是跳转新页面亦或者是执行服务端动作(调接口),但是希望这个动作是界面设计器拖拽进来的。 这篇文章详细的讲解了自定义的视图、字段怎么执行界面设计器拖出来的按钮。 自定义视图 1: 先设计一个页面,把对应的动作拖拽进来,可以不需要配置字段2: 将该页面绑定菜单 3: 自定义对应的页面 当我们自定义视图的时候,首先会注册一个视图,下面是我自定义的一个表单视图 registerLayout( `<view type="FORM"> <element widget="actionBar" slot="actionBar"> <xslot name="actions" /> </element> <element widget="MyWidget" slot="form"> <xslot name="fields" /> </element> </view>`, { moduleName: 'ys0328', model: 'ys0328.k2.Model0000000453', actionName: 'MenuuiMenu78ec23b054314ff5a12b4fe95fe4d7b5', viewType: ViewType.Form } ); 我自定义了一个叫做MyWidget的 element,下面是对应的ts代码 @SPI.ClassFactory(BaseElementWidget.Token({ widget: 'MyWidget' })) export class MyWidgetManageWidget extends FormWidget { public initialize(props): this { super.initialize(props); this.setComponent(MyVue); return this; } } 这是对应的 vue 文件: MyVue.vue <template> <div @click="onClick">点击执行动作</div> </template> <script lang="ts"> import { defineComponent } from 'vue'; export default defineComponent({ props: ['onClick'] }); </script> 这个时候,我希望点击的时候,执行 onClick,会执行对应的动作,这时只需要在对应的 ts 文件中写对应的代码逻辑即可: @SPI.ClassFactory(BaseElementWidget.Token({ widget: 'MyWidget' })) export class MyWidgetManageWidget extends BaseElementWidget { // 获取当前页面所有的按钮 @Widget.Reactive() public get modelActions() { return this.metadataRuntimeContext.model.modelActions || [] } // 用来解析上下文表达式的,如果不需要,可以删除 public executeCustomExpression<T>( parameters: Partial<ExpressionRunParam>, expression: string, errorValue?: T ): T | string | undefined { const scene = this.scene; return Expression.run( { activeRecords: parameters.activeRecords, rootRecord: parameters.rootRecord, openerRecord: parameters.openerRecord, scene: parameters.scene || scene, activeRecord: parameters.activeRecord } as ExpressionRunParam, expression, errorValue ); } // 点击事件 @Widget.Method() public onClick() { // 找到对应的按钮 const action = this.modelActions.find((a) => a.label === '动作的显示名称'); /** * 如果是服务端动作,就执行 executeServerAction */ // executeServerAction(action, 参数对象) // 第二个参数是调用对应的接口传递的参数 /** *…

    2023年11月8日
    90502
  • 左树右表默认选择第一行

    import { BaseElementWidget, Widget, SPI, ViewType, TableSearchTreeWidget } from '@kunlun/dependencies'; @SPI.ClassFactory( BaseElementWidget.Token({ viewType: ViewType.Table, widget: 'tree', model: '改成当前视图的模型' }) ) export class CustomTableSearchTreeWidget extends TableSearchTreeWidget { protected hasExe = false; @Widget.Watch('rootNode.children.length') protected watchRootNode(len) { if (len && !this.hasExe) { this.hasExe = true; const firstChild = this.rootNode?.children?.[0]; if (firstChild) { this.onNodeSelected(firstChild); this.selectedKeys = [firstChild.key]; } } } }

    2024年11月26日
    1.0K00
  • oio-empty-data 空数据状态

    何时使用 当目前没有数据时,用于显式的用户提示。 初始化场景时的引导创建流程。 API 参数 说明 类型 默认值 版本 description 自定义描述内容 string | v-slot – image 设置显示图片,为 string 时表示自定义图片地址 string | v-slot false imageStyle 图片样式 CSSProperties –

    2023年12月18日
    80300

Leave a Reply

登录后才能评论