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.