Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / C#

Creating Per-Session Services with Hiro

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
1 Nov 2011LGPL3 5.6K   1
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)


Written By
Software Developer (Senior) Readify
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questiongood! Pin
natsk4-Jan-13 15:33
natsk4-Jan-13 15:33 
well done!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.