I have written a short example of using Session and also using Cache. I have created a test class called incrementer which is very similar to if I made the class static or at least the variable. RegisterInstance is for a Singleton Resolve
public class Incrementer
{
private int count;
private object synclock = new object();
public int GetCount()
{
return count;
}
public void Increment()
{
System.Threading.Monitor.Enter(synclock);
count++;
System.Threading.Monitor.Exit(synclock);
}
}
public IUnityContainer SessionUnityContainer
{
get
{
if (Session["SharedIncrementer"] == null)
{
IUnityContainer container = new UnityContainer();
container.RegisterInstance<Incrementer>(new Incrementer());
Session["SharedIncrementer"] = container;
}
return Session["SharedIncrementer"] as IUnityContainer;
}
}
public IUnityContainer CacheUnityContainer
{
get
{
if (Cache["SharedIncrementer"] == null)
{
IUnityContainer container = new UnityContainer();
container.RegisterInstance<Incrementer>(new Incrementer());
Cache["SharedIncrementer"] = container;
}
return Cache["SharedIncrementer"] as IUnityContainer;
}
}
protected void Page_Load(object sender, EventArgs e)
{
Incrementer i1 = SessionUnityContainer.Resolve<Incrementer>();
Incrementer i2 = CacheUnityContainer.Resolve<Incrementer>();
for (int i = 0; i < 10; i++)
i1.Increment();
for (int i = 0; i < 5; i++)
i2.Increment();
Response.Write(i1.GetCount().ToString());
Response.Write(i2.GetCount().ToString());
}
Hope tihs helps:
Andrew
EDIT: The following example cimply uses a singleton instance of the UnityContainer and if you keep refreshing the page will see it persisting the values previous.
public class Incrementer
{
private int count;
private object synclock = new object();
public int GetCount()
{
return count;
}
public void Increment()
{
System.Threading.Monitor.Enter(synclock);
count++;
System.Threading.Monitor.Exit(synclock);
}
}
public static class ExampleSettings
{
private static IUnityContainer container = null;
public static IUnityContainer Container
{
get
{
if (container == null)
{
container = new UnityContainer();
container.RegisterInstance<Incrementer>(new Incrementer());
}
return container;
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
Incrementer i1 = ExampleSettings.Container.Resolve<Incrementer>();
for (int i = 0; i < 10; i++)
i1.Increment();
Response.Write(i1.GetCount().ToString());
}