gpt4 book ai didi

c# - Autofac - InstancePerHttpRequest 与 InstancePerLifetimeScope

转载 作者:IT王子 更新时间:2023-10-29 03:47:16 25 4
gpt4 key购买 nike

这两个作用域有什么区别?

我在每一层(存储库、服务、MVC 应用程序)中构建模块(s),但为了拥有InstancePerHttpRequest,您需要 Autofac.Mvc 程序集。

我应该在存储库和服务层中使用哪个范围?

最佳答案

InstancePerHttpRequestInstancePerApiRequest 基本上做同样的事情 - 您为每个离散的网络请求获得一个服务实例。我将使用 InstancePerHttpRequest 来回答剩下的问题,但请记住,这两者是可以互换的。

InstancePerLifetimeScope 意味着将为每个请求您的服务的生命周期范围创建一个新的服务实例。每个 Web 请求都有自己的新生命周期范围,因此在实践中,这两个请求通常会做完全相同的事情。

如果您在 InstancePerHttpRequest 下注册了一项服务,并且您从另一项注册为 SingleInstance 的服务请求其中一项服务,那么唯一真正的区别就在于此。在这种情况下:

  • SingleInstance 组件位于 root 范围内
  • InstancePerHttpRequest 组件位于名为“AutofacWebRequest”的范围内,它是根范围的子级

Autofac 不允许从子范围进行解析 - 所以本质上,SingleInstance 服务无法找到 InstancePerHttpRequest 服务。

但是,如果在这种情况下您使用了 InstancePerLifetimeScope(而不是 InstancePerHttpRequest),那么您的服务会很好地解析。

我写了一篇相当详尽的文章,其中包含可下载的代码,试图详细解释所有这些 - see here .引用文章:

One common misconception here is that registering your component with InstancePerLifetimeScope in a WebAPI application means that your component lives in the scope of a web request – i.e. that “Lifetime” refers to “the Lifetime of the web request”. As you can see here, this is false.

The lifetime of your component is determined by the scope in which it was resolved.

Since the SingletonResolvable resolves its token from the root scope, that token instance lives in the root scope, not the scope of a web request. I’ve said it before, but I’ll say it again: this token will live until the entire application is disposed of (e.g. the IIS worker process is recycled). Anything which asks for a ScopeToken from the root scope will be given a reference to that token.

希望能有所帮助 - 我明白这个问题现在已经很老了,但它仍然非常相关!

关于c# - Autofac - InstancePerHttpRequest 与 InstancePerLifetimeScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12127000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com