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
It looks as though your
HttpServiceclass may be registered as aSingleInstance()(singleton) component. Or, one of the classes that hasIHttpServiceas a dependency is a singleton.When this occurs, even though you’ve set up Autofac to return a new
HttpContextBaseinstance per HTTP request (or lifetime scope, which is also correct) theHttpServiceclass will hang on to whicheverHttpContextBasewas current when the singleHttpServiceinstance was created.To test this theory, try taking a dependency on
HttpContextBasedirectly from a page, and see whether the problem still occurs. Figuring out which is the singleton component should be fairly straightforward if so.