Thursday, September 10, 2009

Creating Per-Session Services with Hiro

Over the past week, I've had a few people ask me how they can use Hiro to create services that are instantiated once per web session. Ideally, Hiro should be able to do something like this:



// Instantiate the IFoo service
var context = HttpContext.Current;

if (context.Session["SomeFooKey"] == null)
context.Session["SomeFookey"] = container.GetInstance<IFoo>();

return (IFoo)context.Session["SomeFooKey"];



The code itself is pretty simple, but the problem is that this can get quite cumbersome if you have more than a few services that need to be stored in the Session object. There has to be some way to do this with Hiro using a single method call, and indeed, Hiro makes creating per-session services just as equally effortless:


// Register the Foo service into the DependencyMap
var map = new DependencyMap();
map.AddPerSessionService(typeof(IFoo), typeof(Foo));

// Compile the container
var container = map.CreateContainer();

var foo = container.GetInstance<IFoo>();

// ...use the IFoo per-session service here (just like any other service)


As you can see from the example above, Hiro abstracted away the details of having to deal with caching your services into a Session object. In fact, all you have to do to add per-session services to your dependency maps is to use the AddPerSessionService extension method, compile your container and use it like any other Hiro-compiled container. It's just that simple.

NOTE: You can download the Hiro.Web extensions (including the per-session service support extension method) here.

2 comments:

  1. Awesome job, I'm really enjoying using Hiro.

    ReplyDelete
  2. Thanks Garren. Let me know if there's anything else I can do to help you.

    Regards,

    Philip Laureano

    ReplyDelete

Ratings by outbrain