Session Scoped Bindings With Ninject 2

An entry about inversion of control | ninject | asp.net | asp.net mvc Publication date 2. June 2010 18:33

Ninject 2 comes out of the box with a set of standard scoping options for activations: transient, singleton, threaded etc. There’s also an ASP.NET specific “request” scope, which ensures that all activations for a binding returns the same instance throughout one request. However, there’s no session scope (at least not that I could dig up), so if you want a scope such that activations of a binding returns the same instance throughout the lifetime of an entire ASP.NET session, you’ll have to roll your own.

Googling for a while, I couldn’t find anyone having blogged about this before. Which I find weird, because surely this is a common scoping requirement for web applications? I guess everyone is too busy twittering these days to blog much (not me though, nu uh :-p).

Anyways, we can roll our own solution for this fairly easily using the InScope() method, which Nate Kohari explains how works like this:

The object returned by the callback passed to InScope() becomes the "owning"
object of instances activated within the scope. This has two meanings:

1. If the callback returns the same object for more than one activation,
Ninject will re-use the instance from the first activation.

2. When the object returned from the callback is garbage collected, Ninject
will deactivate ("tear down", call Dispose(), etc.) any instances associated
with that object.

Armed with this knowledge, all we need to do is ensure that InScope is given a callback that returns the same, unique object for each session. My first idea was to simply pass it HttpContext.Current.Session – but ASP.NET is built so that it rebuilds the HttpContext object (and the Session bag) for each request, so this essentially makes the scoping a request scope. So we’ll need to make things a little bit more complicated:

public static class NinjectSessionScopingExtention

{

    public static void InSessionScope<T>(this IBindingInSyntax<T> parent)

    {

        parent.InScope(SessionScopeCallback);

    }

 

    private const string _sessionKey = "Ninject Session Scope Sync Root";

 

    private static object SessionScopeCallback(IContext context)

    {

        if (HttpContext.Current.Session[_sessionKey] == null)

        {

            HttpContext.Current.Session[_sessionKey] = new object();

        }

 

        return HttpContext.Current.Session[_sessionKey];

    }

}

Here we’re essentially using the ASP.NET session bag to store an object throughout the lifetime of the session, which we can then use as the scope owner. And that’s it, we can now set up bindings InSessionScope().

Check out my session on the Dependency Inversion Principle (track 7, day 3) at NDC 2010 in a couple of weeks for an in depth discussion on taking full advantage of modern IOC containers scoping features.

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.

NDC 2010

The conference to attend this summer happens June 16th-18th in Oslo, Norway. Are you going? Be sure to catch my talk on AOP while you're there!

 

Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS