midwayjs / injection

Injection is a powerful inversion of control container that is widely used in the midway framework and brings good user experience.
MIT License
160 stars 20 forks source link

两个类互相inject导致v8堆栈溢出怎么解决? #22

Closed lblblong closed 4 years ago

lblblong commented 5 years ago

因为确实有这种需求,两个类互相要用对方的方法

:octocat: From gitme Android

lblblong commented 5 years ago

TestService.ts

import { provide, inject } from 'midway'
import { HomeService } from './HomeService'

@provide()
export class TestService {
  constructor() {
    console.log('TestService 实例化')
  }

  @inject()
  homeService: HomeService

  test() {
    return this.homeService.test2()
  }
}

HomeService.ts

import { provide, inject } from 'midway'
import { TestService } from './TestService'

@provide()
export class HomeService {
  constructor() {
    console.log('HomeService 实例化')
  }

  @inject()
  testService: TestService

  test() {
    return this.testService.test()
  }

  test2() {
    return 'hello midway'
  }
}

image image

kurten commented 5 years ago

循环注入这个问题我们这边再看一下有什么解决办法。目前建议拆解一下方法来解决。

czy88840616 commented 5 years ago

一般是抽一个三方 class 来解耦,或者看看怎么 lazyload 了。

lblblong commented 5 years ago

可以用懒加载来解决这个问题,但是就用不上装饰器这个特性了 @kurten @czy88840616 TestService.ts

import { provide } from 'midway'
import { HomeService } from './HomeService'

@provide()
export class TestService {
  constructor() {
    console.log('TestService 实例化')
  }

  get homeService() {
    return new HomeService()
  }

  test() {
    return this.homeService.test2()
  }
}

HomeService.ts

import { provide } from 'midway'
import { TestService } from './TestService'

@provide()
export class HomeService {
  constructor() {
    console.log('HomeService 实例化')
  }

  get testService() {
    return new TestService()
  }

  test() {
    return this.testService.test()
  }

  test2() {
    return 'hello midway'
  }
}
kurten commented 4 years ago

已修复