InversifyJS 已经有inRequestScope()
一段时间了,但它对 container-per-http-request 的情况并没有太大帮助,因为 InversifyJS 的请求范围实际上与单个调用绑定在一起get
,也就是说,每次调用都get
被视为一个请求,并且如果get
每个请求只有一次调用,它只会按预期用于 HTTP 上下文。
我遇到了和你一样的问题:在一个中间件中,我需要从请求中拉出当前用户并将该信息注入到一个CurrentUser
类中,以便以后其他服务可以访问该信息。
为此,我至少需要两次调用get<CurrentUser>
:一个在中间件中,另一个用于实例化请求的控制器/处理程序。
所以,inRequestScope
不是一个可行的解决方案,inSingletonScope
或者inTransientScope
也不可能。
我最终创建了ScopedContainer
您可以在下面看到的课程。
首先,这是你将如何使用它:
// register-global-dependencies.ts
ScopedContainer.globalContainer = (() => {
const container = new Container();
container
.bind<SomeSingletonDep>(TOKENS.SomeSingletonDep)
.to(SomeSingletonDep)
.inSingletonScope();
return container;
})();
☝️ 这允许您仍然拥有单例依赖项。
// register-scoped-dependencies.ts
import "register-global-dependencies";
ScopedContainer.postConfigure((container) => {
container
.bind<RequestSpecificDep>(TOKENS.RequestSpecificDep)
.to(RequestSpecificDep)
.inSingletonScope();
});
☝️ 这控制每个 HTTP 请求应该解决哪些依赖项。
// lambda-handler.ts
import "register-scoped-dependencies";
handler = (event, context) => {
const requestId = event.requestContext.requestId;
const container = ScopedContainer.for(requestId);
try {
// This will be the same for every request
const singletonDep = container.get(TOKENS.SomeSingletonDep);
// And this will be a new instance for every request
const requestSpecificDep = container.get(TOKENS.RequestSpecificDep);
}
finally {
ScopedContainer.remove(requestId);
}
}
这是ScopedContainer
课程:
import { Container, interfaces } from "inversify";
const DEFAULT_SCOPE_ID = "__default__";
type PostConfigureAction = (container: Container) => void;
type ScopedContainerCache = {
[id: string]: Container;
};
class ScopedContainer {
private static _postConfigureActions: PostConfigureAction[] = [];
private static readonly _instances: ScopedContainerCache = {};
/**
* Options object to use when creating a new container for a
* scope ID.
*/
static containerOptions: interfaces.ContainerOptions;
/**
* A global container instance, which enables truly
* singleton instances when using a scoped container. All scoped
* containers reference the global container as parent.
*/
static globalContainer: Container;
/**
* Returns a @see Container that is unique to the specified scope.
* If this is the first time getting the container for the scope, then a
* new container will be created using the provided factory. Any post configure
* actions will also be applied to the new container instance.
* @param scopeId Any string to identify the scope (e.g. current request ID).
* @returns A @see Container that is unique to the specified scope.
*/
static for(scopeId = DEFAULT_SCOPE_ID): Container {
let container = this._instances[scopeId];
if (!container) {
container = this.makeNewContainer();
this._instances[scopeId] = container;
}
return container;
}
/**
* Unbinds the @see Container (i.e. container.unbindAll()) and removes
* it from the cache.
* @param scopeId
*/
static remove(scopeId = DEFAULT_SCOPE_ID): void {
let container = this._instances[scopeId];
if (!container) return;
container.unbindAll();
delete this._instances[scopeId];
}
/**
* Runs the @method remove method on all instances.
*/
static removeAll(): void {
Object.keys(this._instances).forEach((key) => this.remove(key));
}
/**
* Adds a post configure action.
* @param fn A function that will be run everytime a new @see Container is created.
* @returns The @see ScopedContainer itself, to allow chaining.
*/
static postConfigure(fn: PostConfigureAction): ScopedContainer {
this._postConfigureActions.push(fn);
return this;
}
/**
* Removes any post configure actions.
*/
static resetPostConfigureActions(): void {
this._postConfigureActions = [];
}
private static makeNewContainer(): Container {
const container =
this.globalContainer?.createChild(this.containerOptions) ??
new Container(this.containerOptions);
this._postConfigureActions.forEach((action) => action(container));
return container;
}
}
export default ScopedContainer;
https://github.com/inversify/InversifyJS/issues/1076#issuecomment-1045179988