Autofac:从 SingleInstanced 类型到 HttpRequestScoped 的引用
我有一个应用程序,其中共享对象需要引用每个请求对象。
Shared: Engine | Per Req: IExtensions() | Request
如果我尝试将 IExtensions
直接注入到 Engine
的构造函数中,即使是 Lazy(Of IExtension)
,我也会得到“无范围匹配” [请求]从请求实例的范围可见。”当它尝试实例化每个 IExtension
时出现异常。
如何创建 HttpRequestScoped 实例,然后将其注入共享实例?
将其设置在 Request
的工厂中(从而将 Engine
注入 RequestFactory
中)是否被认为是好的做法?
I've got an application where a shared object needs a reference to a per-request object.
Shared: Engine | Per Req: IExtensions() | Request
If i try to inject the IExtensions
directly into the constructor of Engine
, even as Lazy(Of IExtension)
, I get a "No scope matching [Request] is visible from the scope in which the instance was requested." exception when it tries to instantiate each IExtension
.
How can I create a HttpRequestScoped instance and then inject it into a shared instance?
Would it be considered good practice to set it in the Request
's factory (and therefore inject Engine
into RequestFactory
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于
Engine
的共享生命周期要求,您无法将请求范围的扩展注入其中。您可以拥有 Engine 上的方法或属性,它将主动解析当前请求范围中的扩展集合。首先,让
Engine
接受构造函数依赖:然后,在 Autofac 注册中:
Due to the shared lifetime requirements of
Engine
you cannot inject request-scoped extensions into it. What you could have is a method or property on Engine that will actively resolve a collection of extensions from the current request scope.So first, let
Engine
take a constructor dependency:And then, in your Autofac registration: