I want to use AutoFac in a web application. I have a root container, a child container per session, and a child container for each request. I'm trying to figure out what is the best way to manage these areas of life time. In Global.asax.cs, I added the following:
protected void Application_Start(object sender, EventArgs e) { var container = ...; } protected void Session_Start(object sender, EventArgs e) { var sessionScope = container.BeginLifetimeScope("session"); Session["Autofac_LifetimeScope"] = sessionScope; } protected void Application_BeginRequest(object sender, EventArgs e) { var sessionScope = (ILifetimeScope) Session["Autofac_LifetimeScope"]; var requestScope = sessionScope.BeginLifetimeScope("httpRequest"); HttpContext.Current.Items["Autofac_LifetimeScope"] = requestScope; } protected void Application_EndRequest(object sender, EventArgs e) { var requestScope = (ILifetimeScope)HttpContext.Current.Items["Autofac_LifetimeScope"]; requestScope.Dispose(); } protected void Session_End(object sender, EventArgs e) { var sessionScope = (ILifetimeScope)Session["Autofac_LifetimeScope"]; sessionScope.Dispose(); } protected void Application_End(object sender, EventArgs e) { container.Dispose(); }
How can I tell AutoFac to use my Scope request as a starting point for getting dependencies, so that implementations that I register as InstancePerLifetimeScope will be resolved with my requestScope?
If this is not possible, can I get AutoFac to create my goal for the entire request from my sessionScope?
Or am I wrong here? Could there be another way to make AutoFac aware of this hierarchy?
Any help or other comments are appreciated.
In response to Stephen.
I'm still in the early stages of prototyping, but the possible things you might have in a Scope session:
- Find Page
- Authentication and authorization context (e.g. user ID and role)
Not related to the application I'm going to create, but in an e-commerce environment, the cart may be busy in sessions. This is probably the best concrete example. This is what you expect to live longer than the request, but shorter than the application.
It may be more, but if I have a strategy for UserPreferences, Authentication and Authorization, this strategy can also be applied to other components that will be created later.
A possible alternative is to get all the necessary information at the beginning of the request and place these customized components in the request area. This will give me the result that I expect, but it does not match the model that I mean about the application-> session-> query hierarchy. I hope to create a system that makes sense, since I'm definitely not the one that will support it.
Jeroen
source share