How to register HttpContextBase with Autofac in Asp.Net (not MVC)

asp.net, autofac, c#

Solution

It looks as though your `HttpService` class may be registered as a `SingleInstance()` (singleton) component. Or, one of the classes that has `IHttpService` as a dependency is a singleton.

When this occurs, even though you've set up Autofac to return a new `HttpContextBase` instance per HTTP request (or lifetime scope, which is also correct) the `HttpService` class will hang on to whichever `HttpContextBase` was current when the single `HttpService` instance was created.

To test this theory, try taking a dependency on `HttpContextBase` directly from a page, and see whether the problem still occurs. Figuring out which is the singleton component should be fairly straightforward if so.

Problem

This is a Asp.net application (not MVC) running .Net 3.5 I did this: ``` protected void Application_Start(object sender, EventArgs e) { ... builder.Register(c => new HttpContextWrapper(HttpContext.Current)) .As<HttpContextBase>() .InstancePerHttpRequest(); } ``` But it doesn't work. The error I am getting this: No scope with a Tag matching 'httpRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being reqested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself. So then I found this: https://stackoverflow.com/a/7821781/305469 And I did this instead: ``` builder.Register(c => new HttpContextWrapper(HttpContext.Current)) .As<HttpContextBase>() .InstancePerLifetimeScope(); ``` But now when I do this: ``` public class HttpService : IHttpService { private readonly HttpContextBase context; public HttpService(HttpContextBase context) { this.context = context; } public void ResponseRedirect(string url) { //Throws null ref exception context.Response.Redirect(url); } } ``` and I got a Null Reference Exception. Strangely, context.Response is not null, it is when I call .Redirect() that it throw. I am wondering if using .InstancePerLifetimeScope(); is the problem. BTW, I tried using Response.Redirect() and it works perfectly. So what could be the problem? Thanks, Chi

Original source