InstancePerHttpRequest

InstancePerHttpRequest

本文介绍了Autofac - InstancePerHttpRequest vs InstancePerLifetimeScope的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个范围之间有什么区别?



我在每个层中构建模块 (Repository,Service,MVC App),但为了具有 InstancePerHttpRequest ,需要Autofac.Mvc程序集。



我的Repository和Service层应该使用哪个范围?

解决方案

InstancePerHttpRequest InstancePerApiRequest 基本上做同样的事情 - 您可以为每个离散Web请求获取一个服务实例。我将使用 InstancePerHttpRequest 作为答案的其余部分,但请记住,这两个是可互换的。



InstancePerLifetimeScope 意味着将为每个要求您的服务的生命周期范围创建一个新的服务实例。每个网络请求都有自己的新生命周期范围,所以在实践中,通常情况下,这两个将完全相同。



唯一真正的区别是,如果你在 InstancePerHttpRequest 中注册的服务,并且您从另一个注册为 SingleInstance 的服务请求其中一个服务。在这种情况下:




  • SingleInstance 组件住在范围

  • InstancePerHttpRequest 组件的一个范围叫做AutofacWebRequest,这是一个 >的根范围



Autofac不允许从子范围解析 - 基本上, SingleInstance 服务找不到 InstancePerHttpRequest 服务。



但是,如果在这种情况下你已经使用 InstancePerLifetimeScope (而不是 InstancePerHttpRequest ),那么您的服务将解决很好。



我已经写出了一个相当详尽的文章,其中包含可下载的代码,试图详细解释所有这些 - 。引用文章:

希望有帮助 - 我感谢这个问题现在已经很老了,但是它还是很相关的!


What are the differences between the two scopes?

I am building Module(s) in each layer (Repository, Service, MVC App), but in order to have InstancePerHttpRequest you need the Autofac.Mvc assembly.

Which scope should I be using in my Repository and Service layer?

解决方案

InstancePerHttpRequest and InstancePerApiRequest essentially do the same thing - you get a single instance of your service for each discrete web request. I'll use InstancePerHttpRequest for the rest of the answer, but keep in mind that these two are interchangeable.

InstancePerLifetimeScope means a new instance of the service will be created for every lifetime scope which asks for your service. Each web request gets its own fresh lifetime scope, so in practice, more often than not, these two will do the exact same thing.

The only real difference comes if you have a service registered under InstancePerHttpRequest and you request one of those services from another service which is registered as a SingleInstance. In this scenario:

  • The SingleInstance component lives in the root scope
  • The InstancePerHttpRequest component lives in a scope called "AutofacWebRequest", which is a child of the root scope

Autofac does not allow for resolution from child scopes - so essentially, the SingleInstance service cannot find the InstancePerHttpRequest service.

However, if in this scenario you had used InstancePerLifetimeScope (instead of InstancePerHttpRequest), then your services would resolve just fine.

I've written up a fairly exhaustive article with downloadable code that attempts to explain all this in detail - see here. Quoting from the article:

Hope that helps - I appreciate this question is now quite old, however its still very relevant!

这篇关于Autofac - InstancePerHttpRequest vs InstancePerLifetimeScope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 20:16