using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace ScrambledBrains.Nuggets
{
// immutable modification of singleton-per-request pattern
public class ImmutableRequestSingleton<ImmutableType> where ImmutableType : IIdentifiable, new()
{
protected static string _identifier = "ImmutableRequestSingleton<";
private ImmutableRequestSingleton() { }
public static void Initialize(ImmutableType immutableReferenceMember)
{
if (HttpContext.Current.Items[_identifier + (new ImmutableType()).TypeIdentity] == null) // then ImmutableRequestSingleton is uninitialized
{
HttpContext.Current.Items[_identifier + new ImmutableType().TypeIdentity] = new ImmutableRequestSingleton<ImmutableType>();
((ImmutableRequestSingleton<ImmutableType>)(HttpContext.Current.Items[_identifier + new ImmutableType().TypeIdentity]))._immutableReferenceMember = immutableReferenceMember;
}
else
throw new Exception(_identifier + new ImmutableType().TypeIdentity + "> already initialized.");
}
public static ImmutableRequestSingleton<ImmutableType> Current
{
get
{
if (HttpContext.Current.Items[_identifier + new ImmutableType().TypeIdentity] == null)
return (ImmutableRequestSingleton<ImmutableType>)null; // throw new Exception("ImmutableRequestSingleton not initialized.");
else
return (ImmutableRequestSingleton<ImmutableType>)HttpContext.Current.Items[_identifier + new ImmutableType().TypeIdentity];
}
}
// note: readonly modifier is not used, but writing is controlled conditionally within Initialize()
private ImmutableType _immutableReferenceMember;
public ImmutableType ImmutableReferenceMember
{
get { return _immutableReferenceMember; }
}
}
public interface IIdentifiable
{
string TypeIdentity { get; }
}
}