0

我使用 inversify,我有一些看起来像这样的代码:

export const bindings = new AsyncContainerModule(async (bind) => {

await require("./controllers/BaseController");
await require("./controllers/ContentController");

bind<CssLoader>(TYPE.CssLoader).to(CssLoader).inSingletonScope();
bind<GQLQueryLoader>(TYPE.GQLQueryLoader).to(GQLQueryLoader).inSingletonScope();
bind<GQLRepository>(TYPE.GQLRepository).to(GQLRepository).inSingletonScope();
bind<ArticleRenderer>(TYPE.ArticleRenderer).to(ArticleRenderer).inSingletonScope();
bind<GuideRenderer>(TYPE.GuideRenderer).to(GuideRenderer).inSingletonScope();
bind<RendererFactory>(TYPE.RendererFactory).to(RendererFactory).inSingletonScope();
bind<HeaderAndFooterManager>(TYPE.HeaderAndFooterManager).to(HeaderAndFooterManager).inSingletonScope();});

我的问题是我需要在注册 GQLQueryLoader 之后才注册 HeaderAndFooterManager,因为它仅在加载后才使用查询。

该容器在应用程序中使用如下:

(async () => {
const staticServer = express();
staticServer.use(express.static(path.join(__dirname, 'public')));

staticServer.engine('handlebars', exphbs({  }));
staticServer.set('view engine', 'handlebars');
staticServer.set('views', path.join(__dirname, '..', 'views'));


const PORT = process.env.PORT || 3000;
const container = new Container();
await container.loadAsync(bindings);

const app = new InversifyExpressServer(container, null, null, staticServer);
const server = app.build();

server.listen(PORT, () => {
    console.log(`Server running on port ${PORT}/`)
}); })();

编辑>>> T问题是服务器启动时两个服务都需要在构造函数中初始化一些状态。GQLQueryLoader 需要从磁盘加载查询并提供对它们的访问,因此我不必在每次请求时从磁盘读取,并且 HeaderAndFooterManager 需要在构造函数中执行一些查询,以便在服务器启动时缓存结果,以便我将该信息保存在内存中,但它需要访问 GQLQueryLoader 加载的查询。我所做的不是在第一次需要之前初始化页眉和页脚数据。我检查是否加载,如果没有加载它。但是,这只是一种解决方法,并且感觉这是一种重要的问题,知道如何以干净的方式解决。

4

0 回答 0