Created
May 18, 2021 05:07
-
-
Save holyshared/9a927b0c73d5532a2bc8f29881f92ef6 to your computer and use it in GitHub Desktop.
awilix example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createContainer, asValue, asFunction, asClass } from "awilix"; | |
// 関数で生成する | |
// 引数は予めコンテナで設しておく | |
const loggerFactory = ({ path }: { path: string }) => { | |
return { | |
path | |
}; | |
}; | |
class ConstructorInjectionLogger { | |
private path: string; | |
constructor(path: string) { | |
this.path = path; | |
} | |
} | |
class ProxyInjectionLogger { | |
private path: string; | |
constructor({path} : {path: string}) { | |
this.path = path; | |
} | |
} | |
const container = createContainer(); | |
container.register({ | |
path: asValue("/tmp"), | |
logger: asFunction(loggerFactory), | |
loggerByProxyInjection: asClass(ProxyInjectionLogger).singleton(), // | |
loggerByConstructorInjection: asClass(ConstructorInjectionLogger).classic().singleton() // コンストラクタで依存する物をもらう | |
}); | |
const logger = container.resolve("logger"); | |
console.log(logger); | |
const loggerByProxyInjection = container.resolve("loggerByProxyInjection"); | |
console.log(loggerByProxyInjection); | |
const loggerByConstructorInjection = container.resolve("loggerByConstructorInjection"); | |
console.log(loggerByConstructorInjection); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment