问题描述
我有哪里的共享对象需要每个请求对象的引用的应用程序。
I've got an application where a shared object needs a reference to a per-request object.
Shared: Engine
|
Per Req: IExtensions()
|
Request
如果我试图注入 IExtensions
直接进入引擎
的构造函数,即使懒惰(中IExtension)
,我得到一个没有匹配的范围[请求]是其中要求该实例的范围是可见的。异常时,它会尝试实例每个 IExtension
。
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
.
我如何创建的Htt prequestScoped实例,然后将其注入一个共享实例?
How can I create a HttpRequestScoped instance and then inject it into a shared instance?
难道被认为是很好的做法,将其设置在请求的
厂(因此注入引擎
进入 RequestFactory
)?
Would it be considered good practice to set it in the Request
's factory (and therefore inject Engine
into RequestFactory
)?
推荐答案
由于发动机的使用寿命共享要求
你不能注入请求范围的扩展了进去。你可能是发动机的方法或属性,将积极从目前的请求范围扩展解决的集合。
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:
public class Engine
{
public Engine(..., Func<IExtensions> extensionsPerRequest)
{
_extensionsPerRequest = extensionsPerRequest;
}
public IExtensions Extensions
{
get { return _extensionsPerRequest(); }
}
}
然后,在你的Autofac注册:
And then, in your Autofac registration:
builder.Register<Func<IExtensions>>(c => RequestContainer.Resolve<IExtensions>());
这篇关于Autofac:从SingleInstance'd类型引用到的Htt prequestScoped的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!