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

依赖注入DI(Dependency Injection) in awilix #3

Open
yizihan opened this issue Jan 31, 2018 · 0 comments
Open

依赖注入DI(Dependency Injection) in awilix #3

yizihan opened this issue Jan 31, 2018 · 0 comments

Comments

@yizihan
Copy link
Owner

yizihan commented Jan 31, 2018

依赖注入DI(Dependency Injection) in awilix

  • 不需要引用模块
  • 不需要自己去实例化
const awilix = require('awilix');

// 创建一个容器并将注入模式设置为代理
const container = awilix.createContainer({
	// 注入模式 => PROXY
	injectionMode: awilix.InjectionMode.PROXY
})

// 一个基本的Controller类
class UserController {
	// 使用constructor 将其他实例化后的类(userService)注入到自己
	constructor (opts) {
		for( var key in opts) {
			console.log(key)		
			// userController  userService
			// opts 保存注册进container里的内容
		}
		// 保存对userService的引用
		this.userService = opts.userService
	}
	getUser (ctx) {
		// 调用userService的内部函数
		return this.userService.getUser(22)
	}
}

// 在container内部注册一个UserController类
container.register({
	userController: awilix.asClass(UserController)
})

// 一个基本的工厂函数
const makeUserService = () => {
	return {
		getUser: (id) => {
			return id + 44;
		}
	}
}

// 在container内部注册一个makeUserService函数
container.register({
	userService: awilix.asFunction(makeUserService)
})

// 使得UserController的实例直接调用makeUserService的方法
console.log(container.resolve('userController').getUser())

比较

依赖注入少了引入模块和实例话的过程

// 正常模式
import IndexModel from '/models/IndexModel';                // 引入服务
class IndexController {
    constructor () {}
    index () {
        return async(ctx, next) => {
            const indexModelIns = new IndexController();    // 实例化
            const result = await indexModelIns.getData();   // 调用服务的方法
        }
    }
}

// 依赖注入模式
class IndexController {
    constructor (opts) {        // opts 保存了所有注册进container里的内容
        // 从参数中获取实例
        this.indexservice = opts.service.indexModelIns; 
    }
    index () {
        return async (ctx, next) => {
            // 直接调用实例的方法
            const result = await this.indexservice.getData();
        }
    }
}
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

1 participant