5

I want to use AutoFac in a web application. I have the root container, a child container per session and a child container per request. I'm trying to figure out what the/a best way is to manage these lifetime scopes. In the Global.asax.cs I have 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();
}
  1. How can I tell AutoFac to use my requestScope as the starting point for getting dependencies, so that the implementations I register as InstancePerLifetimeScope will be resolved using my requestScope?

  2. If that is not possible, can I get AutoFac to create its per-request lifetime scope out of my sessionScope?

  3. Or am I on the wrong track here? Could there be an other way of making AutoFac aware of this hierarchy?

Any help or other comments are appreciated.


In response to Steven.

I'm still in the early stages of prototyping, but possible things you could have in the sessionScope:

  • UserPreferences
  • Authentication and authorization context (e.g. user identity and roles)

Not related to the application I'm going to build, but in a e-commerce environment, the shopping cart could be session scoped. This is probably the best concrete example. It is something that you expect to live longer than a request, but shorter than the application.

There could be more than this, but if I have a strategy for the UserPreferences, Authentication and Authorization, then that strategy could 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 configured components in the request scope. It will give me the result I expect, but it doesn't match the model I have in my mind about application->session->request hierarchy. I'm hoping to create a system that makes sense, since I'm definitely not the one that is going to maintain it.

Jeroen
  • 979
  • 1
  • 7
  • 16
  • What services do you wish to register with a per session scope? This is needed for us to give a good answer on question 3 "am I on the wrong track here?". – Steven Jul 31 '12 at 20:16

1 Answers1

13

What you'll need to do is implement your own Autofac.Integration.Mvc.ILifetimeScopeProvider. This interface is what governs how/where request lifetime scopes get generated. The default one, Autofac.Integration.Mvc.RequestLifetimeScopeProvider, handles creation, disposal, and maintenance of lifetime scopes on a per-request basis.

You can browse the code for RequestLifetimeScopeProvider here, which I highly recommend doing if you plan on undertaking this. It's the best sample I can think of containing working code showing the responsibility of one of these things.

Your implementation of ILifetimeScopeProvider will be where you grab the session child container, spawn the request container from that, and, at the end of the request, clean up the request container. You may also want to create the session container in there if it doesn't exist. Handling cleanup/disposal of the session container may be tricky in there, but from a design perspective, it'd be nice if it was all in one place rather than some in the provider, some in your application class.

Once you have your ILifetimeScopeProvider you'll use it when you set up your dependency resolver.

var scopeProvider = new MyCustomLifetimeScopeProvider(container, configAction);
var resolver = new AutofacDependencyResolver(container, scopeProvider);
DependencyResolver.SetResolver(resolver);

A couple of words of warning about the notion of a session-level scope:

  1. Your memory footprint could be huge. You're going to end up with a lifetime scope for every user on your system. While a request lifetime pops up and goes away pretty quickly, these session-level scopes will live potentially a long time. If you have a lot of session-scoped items, you're going to have a pretty good sized memory usage for each user. If people "abandon" their sessions without properly logging out, that's all the longer these things will live.
  2. Lifetime scopes and their contents aren't serializable. Looking at the code for LifetimeScope, it's not marked [Serializable]... and even if it was, the resolved objects living in there are not necessarily all marked serializable. This is important because it means your session-level lifetime scope might work on a single box with in-memory session, but if you deploy to a farm with SQL session or a session service, things will fall apart because the session can't serialize your stored scope. If you choose not to serialize the scope, then you have a different scope for each user across machines - also a potential problem.
  3. Session isn't always rehydrated. If the handler being accessed (e.g., the web form) doesn't implement IRequiresSessionState, the session won't be rehydrated (whether it's in-proc or not). Web forms and the MvcHandler implement that by default so you won't see any issues, but if you have custom handlers that require injection you'll hit some snags since "Session" won't exist for those requests.
  4. Session_End doesn't always fire. Per the docs on SessionStateModule.End, if you use out-of-proc session state you won't actually get the Session_End event, so you won't be able to clean up.

Given the restrictions, it's generally good to try to stay away from session-stored scopes. However... if that's what you're going to do, the ILifetimeScopeProvider is the way to do it.

Brandon Cuff
  • 1,438
  • 9
  • 24
Travis Illig
  • 23,195
  • 2
  • 62
  • 85
  • Nicholas Blumhardt posted an article at CodeProject [describing this hierarchy](http://www.codeproject.com/Articles/25380/Dependency-Injection-with-Autofac#using-scope-to-control-visibility). But that article just gives some bad advice? I can imagine there are components that will have the same lifetime as the session, so it looked like a good way to go. The application will not have a lot of users and there is no need to deploy it on a farm. But you raised some valid points. – Jeroen Jul 31 '12 at 08:10
  • And 2b, you will have a memory leak in your application when scaling out to a web farm, since `Session_End` will never be called when using an out-of-proc session state. – Steven Jul 31 '12 at 13:53
  • In that article I don't think Nick was "giving advice" so much as using session to provide a more concrete example for explaining how nested hierarchies can work. – Travis Illig Jul 31 '12 at 15:01
  • Good point, @Steven - I added that to the list of issues as well as a note indicating that if you don't implement IRequiresSessionState then you won't have a session... which means no session container, either. – Travis Illig Jul 31 '12 at 15:16
  • @Steven: It won't be the next twitter. Scaling to a web farm won't be needed. – Jeroen Jul 31 '12 at 19:18
  • @TravisIllig: Maybe advice is not the best term, but I suspect the creator of AutoFac won't give an example like this if it is considered bad. Is there an other way of having objects that live as long as the user is connected? There is a huge gap between the lifetime of the application and a request. – Jeroen Jul 31 '12 at 19:27
  • Feel free to ask Nick directly on the Autofac Google Group mailing list. Difficult concepts are made easier if a concrete example is provided, but it's hard to come up with a simple concrete example for nested lifetime scopes that most people will understand if it isn't session. There is no recommended way of doing what you're asking without a non-trivial amount of work due to all of the aforementioned pitfalls. I'm not trying to be difficult, that's just how it is. – Travis Illig Aug 01 '12 at 17:57
  • @TravisIllig: Almost forgot that Google also has one of those Q&A things. I'll see what Nicholas has to say about this, if he says the same thing, I'll accept your answer. Thanks for your time and valuable input. – Jeroen Aug 02 '12 at 08:48
  • @TravisIllig: I've been looking into the AutoFac Google group and it seems that registering those components in the request-scope that might access session state is answer given there the most. It still feels nasty. Implementing an `ILifetimeScopeProvider` is also an alternative. I'll just have to think about it some more (luckily the project won't start for several weeks). Thanks. – Jeroen Aug 12 '12 at 09:55