Unity - PerThreadLifetimeManager

by 20. July 2008 02:27

When Chris Tavares extended an invitation to the Unity Community to review his draft of some documentation (and a sample) on writing custom lifetime managers I saw this is an opportunity to exercise my newly learned Unity knowledge to create another MVP application from scratch.  The primary objective was to learn from Chris on how to extend the Unity container and a secondary objective to see if I could satisfy a requirement that skbach had previously inquired about in the Unity Forum; Lifetime - Between Transient and Signleton? PerWebRequest maybe?

The following excerpt from the Unity Documentation under Key Scenarios | Setting Up the Unity Container is pertinent to understanding the requirement:

By default, the object instances returned by the container when you use the RegisterType method have a transient lifetime. The container does not store a reference to the object, and you will get a new instance of the type each time you call the Resolve method. If you want to manage the lifetime of the object, you specify a lifetime manager when you call the RegisterType method. 

Vision statement: Create an application that will instantiate a new DataContext for each thread while sharing the DataContext if multiple services use the DataContext on the same thread.

To meet this I created three buttons that execute three services:  GenericService, SpecializedService and BothServices (where BothServices will share the DataContext on the same thread).  The DataContext has the following interface:

public interface IDataContext
    DateTime Instantiated { get; set; }
    DateTime LastAccessed { get; set; }
    long Ticks { get; set; }

The Ticks property will represent the Ticks value at the time the class was instantiated; this will permit us to log values in milliseconds to see if the PerThreadLifetimeManager is working correctly

Disclaimer: When I created this application it was in the context of testing Chris Tavares's documentation; thus the title reflects the purpose of the application - it is not an endorsement from Chris nor is it associated with him in any way.   I have only been working with Unity for a few months and the code reflects newbie status - not Chris' guru status.

Download source code (C#) LifetimeManager.zip (1.45 mb)



Blog videos and references to CodePlex projects are no longer valid