c# - Autofac - InstancePerHttpRequest 与 InstancePerLifetimeScope

标签 c# asp.net-mvc-3 dependency-injection autofac

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

我在每一层(存储库、服务、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/

相关文章:

Ajax.ActionLink 没有 href 属性以获得更好的 SEO

c# - MVC 重定向到默认路由

java - 将工厂模式转换为 Guice 模块

javascript - ionic 2 页面和模态之间的依赖注入(inject)

c# - MVC 3 发送类 JSON

c# - MVC 6 IUrlHelper 依赖注入(inject)

c# - 完成锁定消息时出现 Azure 服务总线 MessageLockLostException

c# - 如何根据传递给 ASP.NET MVC 中的 Controller /操作的属性值有条件地绑定(bind)到 ninject?

c# - 插入日期时间错误

c# - "String was not recognized as a valid DateTime."Window 7电脑环境出现错误