Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于 loadService #4

Open
Joursion opened this issue Mar 14, 2018 · 2 comments
Open

关于 loadService #4

Joursion opened this issue Mar 14, 2018 · 2 comments

Comments

@Joursion
Copy link

我们想要在controller中使用this.ctx.service.check.index();这样的形式,那我们必须要对ctx.service的getter进行重写。
我们在controller中可能会多次使用到this.ctx.service对象,所以我们必须要对其进行缓存,不然每次使用,我们都遍历service文件夹,导入模块,重新生成所有service对象,再挂载,我们的性能会急剧下降。

如果直接在外部初始化,是不是就不需要缓存了?这两种写法有什么 优劣吗?(loadConfig 好像也是类似这么实现的)

loadService() {
    const services = fs.readdirSync(__dirname + '/service');
    const loaded = {};

    services.forEach(serivce => {
        const name = serivce.split('.')[0];
        const mod = require(__dirname + '/service/' + services);
        loaded[name] = new mod(this);
    })

    Object.defineProperty(this.app.context, 'service', {
        get() {
            return loaded
        }
    })
}
@Foveluy
Copy link
Member

Foveluy commented Mar 14, 2018

@Joursion 我们要保证每个service的生命周期和context是一样的,也就是说,每一条链接,我们需要一个新的context、controller、service。

@liangtongzhuo
Copy link

@Foveluy 这样有什么意义呢? service 状态的原因吗?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants