Using ASP.NET Session for Lifetime Management

Mar 31, 2009 at 8:54 PM
I am considering using Unity to manage the lifetime of a custom user class instance.  I am planning on extending the LifetimeManager with a custom ASP.NET session manager.  What I want to be able to do is store and retrieve the currently logged in user object from my custom classes, and have Unity get the instance of User from the session object in ASP.NET, or (when in a Win32 project) retrieve it statically or from the current thread.

So far my best solution is to create a static instance of my Unity container on startup, and use the Resolve method to get my User object from each of my classes.  However, this seems to create a dependency on the unity container in my other classes.  What is the more "Unity" way of accomplishing this goal.  I would like to be able to read/replace the current User instance from any class.
Dec 18, 2009 at 1:11 AM

The design you're talking about is called Service Location - where, when you need something you depend on, you reach out and make a call on another object (the service locator) to get it. You are correct that this design couples you to the locator (the Unity container in this case).

The alternative is to use Dependency Injection - when an object needs the current User, it takes it as a constructor parameter or property. Then you get that object from the container instead, and the container will fill in the dependency. This way, you don't couple the object to the container itself.

See Martin Fowler's description of the two patterns for more information.