ASP.NET Web Forms中InstancePerLifetimeScope与InstancePerRequest的区别
Hey there! Great call verifying with breakpoints and hash codes—let’s break down why you’re seeing both registration styles create a single instance per HttpRequest.
First, let’s clarify what each registration does
InstancePerRequest: This is a web-specific Autofac extension built explicitly for ASP.NET (including Web Forms). It binds your service instance to the top-level HttpRequest lifecycle scope that Autofac automatically spins up for every incoming request. When the request finishes, this scope gets disposed, and so does your instance.InstancePerLifetimeScope: This is a more general-purpose registration that ties the instance to the current active lifecycle scope. In standard Web Forms request processing, the only active scope you’ll interact with is that same top-level HttpRequest scope Autofac creates. So without any custom nested scopes, this behaves exactly likeInstancePerRequest.
Why they act identical in your testing
In a typical Web Forms request flow (no manually created nested scopes), there’s only one lifecycle scope per request. Both registrations resolve instances from this single scope, so you’ll only see one constructor call and one unique hash code per request—hence the matching behavior you observed.
The real difference shows up with nested scopes
The split becomes obvious when you create a child lifecycle scope within a request. For example:
using (var childScope = container.BeginLifetimeScope()) { // With InstancePerLifetimeScope: resolves a NEW instance tied to this child scope var service1 = childScope.Resolve<IMyService>(); // With InstancePerRequest: resolves the SAME instance from the top-level request scope var service2 = childScope.Resolve<IMyService>(); }
InstancePerLifetimeScopecreates a new instance for every nested scope, since it’s bound to the immediate scope it’s resolved from.InstancePerRequestignores nested scopes entirely, always pulling the instance from the root HttpRequest scope—so you’ll reuse the same instance across all child scopes in that request.
Which should you choose?
- Use
InstancePerRequestto make your intent clear: this service is explicitly tied to the web request lifecycle. It’s more readable for Web Forms-specific code. - Use
InstancePerLifetimeScopeif you need a registration that works across web and non-web contexts (like background jobs), or if you want to allow new instances in nested scopes intentionally.
内容的提问来源于stack exchange,提问作者Gianluigi Liguori

