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 1 people

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

NoSQL: Getting started with MongoDB and NoRM

An entry about nosql Publication date 23. March 2010 13:50

Be honest now: did you perform any form of analysis before deciding on using a relational database for your current project? Probably not. Sure, you need some form of persistent storage – but a RDBMS? Probably not. I’ll leave it to Greg Young and Rob Conery to convince you why you’d want to consider other options – in this post I’d like to give you a gentle introduction to getting up and running with MongoDB.

MongoDB?

“MongoDB (from "humongous") is a scalable, high-performance, open source, schema-free, document-oriented database.”

Go download MongoDB and unzip it somewhere. Next, create a folder called data on your root c drive – this is where MongoDB will persist stuff to (you can override the location via its config, but lets keep things simple for this demo).

Next, fire up the MongoDB daemon by executing the mongod.exe file. That’s it! Database installed and ready to be used. Bit less pain than that SQL Server setup wizard, no?

NoRM

In order to access our MongoDB instance from a .NET project, we’ll need some sort of connector. Some really cool guys led by Andrew Theken have created just that, called NoRM. You’ll need to go to the projects github repository, download the source code (click the “Download Source” button, top left) and compile it yourself – but you can handle that, right? Cool. Once you’ve done that, fetch the norm.dll file from the bin folder.

Create yourself a new project in Visual Studio and reference the norm.dll file. Now we’re all set! The cool thing about MongoDB is that we don’t need to define no database or schema or whatever first, we can just start chucking objects into it. But first, we need some classes. Create yourself a simple domain model to run some tests with – or just copy/paste mine:

public class Person

{

    [MongoIdentifier]       

    public SocialSecurityNumber SocialSecurityNumber { get; set; }

 

    public string Name { get; set; }

 

    public int Age { get; set; }

 

    public Gender Gender { get; set; }

 

    public override int GetHashCode()

    {

        return SocialSecurityNumber.GetHashCode();

    }

}

 

public class SocialSecurityNumber

{

    public string Number { get; set; }

 

    public override int GetHashCode()

    {

        return Number.GetHashCode();

    }

}

 

public enum Gender

{

    Male,

    Female

}

Notice the MongoIdentifier attribute – the only reason I needed this was because I wanted to use a natural primary key (and notice that the type of my key is in fact a complex object itself). If you have an property called ID which is either a Guid or ObjectID, then NoRM will automatically pick this up.

Right, time to execute some code. Let’s add a few persons to our database:

[TestFixture]   

public class Adding_Persons_to_database

{

    [Test]

    public void Can_add_persons_to_database()

    {

        // create a provider. "testdb" is the name of our db -

        // it gets created automatically if it doesn't exist yet

        var provider = new MongoQueryProvider("testdb");

 

        // let's make sure there are no Persons in the db

        provider.DB.DropCollection(typeof(Person).Name);

 

        var ben = new Person

                         {

                             Age = 27,

                             Gender = Gender.Male,

                             Name = "Ben",

                             SocialSecurityNumber = new SocialSecurityNumber {Number = "1"}

                         };

 

        var bob = new Person

        {

            Age = 12,

            Gender = Gender.Male,

            Name = "Bob",

            SocialSecurityNumber = new SocialSecurityNumber { Number = "2" }

        };

 

        // this is where we insert into the db

        provider.DB.GetCollection<Person>().Insert(ben);

        provider.DB.GetCollection<Person>().Insert(bob);

 

        // this is how we query the db

        var NumberOfPersons = new MongoQuery<Person>(provider).Count();

 

        Assert.That(NumberOfPersons, Is.EqualTo(2));

    }

}

Okay, so this was a fairly primitive example. But look at what’s not here: no database to set up, no table schemas to define, no object-to-relational mapping to configure. This is just plug and play persistence, pure and simple. Sure, there are limitations and weaknesses and trade-offs to be considered when comparing an object/document DB to a relational DB, and the NoRM API is pretty infantile yet - but the whole NoSQL thing is something that beggs further investigation in my opinion because on the surface it looks pretty damn cool.

Currently rated 5.0 by 5 people

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

Speaking at NDC 2010

An entry about conferences Publication date 22. March 2010 13:14

With 135 sessions held by more than 50 speakers across 7 tracks in 3 days, the conference to attend this year kicks off June 16th in Oslo, Norway. Not convinced? Check out the agenda.

Alongside stalwarts like Robert Martin and Scott Bellware, this years conference features a few underdogs on the agenda, including myself! I’ve been lucky enough to be given a slot on day three to do a session on Aspect Oriented Programming – I haven’t planned out my presentation completely yet, but I can reveal already that I have some pretty ambitious plans to make it worth your while should you choose to attend it ;-)

So. NDC 2010. Oslo Spektrum. June 16th-19th. Get your ticket now.

Be the first to rate this post

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

The Honing of Skills

An entry about craftsmanship Publication date 4. December 2009 10:28

A couple of months back I spoke at the MSDN Live conferences in Norway. One of my talks was on ASP.NET 4.0, and I had some demo code that I used to explain some of the new features. Recently I got some feedback that some people had been baffled about the “quality” of my demo code – why would I bother to write unit tests, apply design patterns and so forth in a silly little demo application? Surely that’s overkill and a sign that I was prone to overengineering my code.

Practice makes perfect

If you want to become good at something, you need to practice. We often talk about this in terms of internalizing a certain set of skills; practicing something until it becomes second nature to do it. There are many ways to accomplish this. One that’s become popular lately, is katas. A kata is a Japanese concept, which basically means to practice a fixed choreography over and over.

Check out this recording of Uncle Bob Martin performing his Prime Factors kata, in which he’s honing his TDD skills in Ruby:

Another great example is this video by Chad Myers, in which he implements FizzBuss in less than 4 minutes with the mouse disabled:

Solving small, insignificant-seeming problems in order to try out and practice methodologies, technologies or patterns is a great way to become familiar with these so that they are in your toolbox ready to be applied instantly when you’re on a deadline and don’t have time to fool around.

Currently rated 5.0 by 2 people

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

ASP.NET MVC 2 at NNUG in Bergen

An entry about nnug | community | conferences Publication date 22. November 2009 21:00

Things have been unfortunately quiet on this blog lately, as I’ve been too busy with other engagements this fall to spend much time blogging. Hopefully I’ll be able to make amends for that this Christmas as things quiet down for the holiday season – so please don’t unsubscribe from my feed quite yet :-)

Until then, if you’re in Bergen this week be sure to drop by the local NNUG meeting on Wednesday where I’ll be giving a presentation about ASP.NET MVC 2. Details are here (in Norwegian).

Be the first to rate this post

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

MSDN Live & GeekBeer: Coming to a City Near You!

An entry about conferences Publication date 4. September 2009 08:47

So it seems summer has already left us – not that it made big of an impression this year, at least not here on the east coast of Norway. But fear not – autumn is not such a bad time to be alive either. Microsoft announced the MSDN Live events in September a few weeks back – since then more than 1000 people have signed up. Read my previous post for more information on when and where if you haven’t signed up already - this is going to rock!

Geek? Beer!

Each of the cities visited by MSDN Live will also be host to an informal social gathering where you can meet the speakers, chat with fellow developers and enjoy a pint (or three).

Here are the details:

Stavanger, September 15th at Timbuktu from 7pm.
Bergen, September 21st at Biskopen from 7pm.
Trondheim, September 23rd at Den Gode Nabo from 7pm.
Oslo, September 29th at Internasjonalen from 4.30pm.

Notice that all of these are the night before the MSDN Live event in that city – except in Oslo, where we’re going to the pub straight after the event to celebrate a (hopefully) successfully finished tour. Be sure to join us in your city if you can! No registration is neccessary, just show up and BYOB :)

Be the first to rate this post

  • Currently 0/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