Skip to content

Instantly share code, notes, and snippets.

@sebnilsson
Last active December 18, 2015 07:39
Show Gist options
  • Save sebnilsson/5748752 to your computer and use it in GitHub Desktop.
Save sebnilsson/5748752 to your computer and use it in GitHub Desktop.
Lazy init objects stored in the current ASP.NET-request.
public class RequestLazy<T>
{
private readonly Func<T> valueFactory;
private readonly Func<IDictionary> storeFactory;
internal RequestLazy(Func<T> valueFactory, string storeKey, Func<IDictionary> storeFactory)
{
this.storeFactory = storeFactory ?? (() => (HttpContext.Current != null) ? HttpContext.Current.Items : null);
this.valueFactory = valueFactory ?? this.GetValue;
this.StoreKey = string.Format("RequestLazy_{0}", storeKey ?? Guid.NewGuid().ToString());
}
public RequestLazy(string storeKey)
: this(null, storeKey)
{
}
public RequestLazy(Func<T> valueFactory, string storeKey = null)
: this(valueFactory, storeKey, null)
{
}
public string StoreKey { get; private set; }
public T Value
{
get
{
if (this.ContextStore == null)
{
return this.valueFactory();
}
if (!this.ContextStore.Contains(this.StoreKey))
{
this.ContextStore[this.StoreKey] = this.valueFactory();
}
return this.GetValue();
}
set
{
if (this.ContextStore == null)
{
return;
}
this.ContextStore[this.StoreKey] = value;
}
}
private IDictionary ContextStore
{
get
{
return this.storeFactory();
}
}
public bool IsValueCreated
{
get
{
return this.ContextStore != null && this.ContextStore.Contains(this.StoreKey);
}
}
public override string ToString()
{
return this.IsValueCreated ? this.Value.ToString() : "(Value not created)";
}
private T GetValue()
{
var item = this.ContextStore[this.StoreKey];
return item is T ? (T)item : default(T);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment