Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Creating Per-Session Services with Hiro

0.00/5 (No votes)
1 Nov 2011LGPL3 5.8K  
How to use Hiro to create services that are instantiated once per web session

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:

C#
// 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:

C#
// 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.

 

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)