Autofac:从 SingleInstanced 类型到 HttpRequestScoped 的引用

发布于 2024-08-28 19:56:01 字数 482 浏览 1 评论 0原文

我有一个应用程序,其中共享对象需要引用每个请求对象。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

轮廓§ 2024-09-04 19:56:01

由于 Engine 的共享生命周期要求,您无法将请求范围的扩展注入其中。您可以拥有 Engine 上的方法或属性,它将主动解析当前请求范围中的扩展集合。

首先,让 Engine 接受构造函数依赖:

public class Engine
{
    public Engine(..., Func<IExtensions> extensionsPerRequest) 
    {
        _extensionsPerRequest = extensionsPerRequest;
    }


    public IExtensions Extensions
    {
       get { return _extensionsPerRequest(); }
    }
 }

然后,在 Autofac 注册中:

builder.Register<Func<IExtensions>>(c => RequestContainer.Resolve<IExtensions>());

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(); }
    }
 }

And then, in your Autofac registration:

builder.Register<Func<IExtensions>>(c => RequestContainer.Resolve<IExtensions>());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文