Am I misunderstanding WebRequestLifestyle?

Sep 22, 2014 at 10:32 PM
Some months back I built an ASP.NET MVC site that is using SimpleInjector. I'd configured a number of objects to have a per-web-request lifecycle.

A couple of these need to register with lambdas that call specific constructors. Because these are registered as per-web-request, I'd expect that a breakpoint to be hit only once per page request. But I'm seeing the method being called multiple times - once for each time the object is injected.

My SimpleInjectorInitializer:
public static class SimpleInjectorInitializer
    public static void Initialize()
            var container = new Container();


            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        private static void InitializeContainer(Container container)
            var webLifestyle = new WebRequestLifestyle();
            container.Register<ILogger, DbLogger>(webLifestyle);

            // Don't add logging to the LoggingDbContext
            container.Register<LoggingDbContext>(() =>
                    // Because we've added a second public constructor, we need to 
                    // call the one we want to use explicitly
                    var db = new LoggingDbContext();
                    return db;
                }, webLifestyle);

                // ...
I'd expect a breakpoint at "return db" to be hit only once, in a page load, but it's being hit multiple times.

Am I simply not understanding how this is intended to work?
Sep 23, 2014 at 6:32 AM
No, you are not misunderstanding the WebRequestLifestyle. It ensures that only one instance is created per web request and will ensure that a registered delegate is just called once. If there is no active web request, an exception will be thrown (compared to other DI libraries that either return a transient or a singleton).

This behavior is tested and many developers are depending on this exact behavior. So my first impression is that there are actually multiple requests. I've had this myself multiple times where I thought the web request lifestyle was broken, while in the end there were async postbacks from the client, or the browser requested images and javascript files, and this caused MVC to start a request and caused objects to be resolved.

Take a look at the call stack while you're in the break point and take a look at the HttpContext.Current.Request information to find out more information about the request. You will probably find out that each breakpoint has its own unique request.
Marked as answer by dot_NET_Junkie on 9/28/2014 at 4:02 AM