Skip to content

Instantly share code, notes, and snippets.

@sheastrickland
Created January 16, 2013 04:07
Show Gist options
  • Save sheastrickland/4544568 to your computer and use it in GitHub Desktop.
Save sheastrickland/4544568 to your computer and use it in GitHub Desktop.
Lazy stuffs
public class LazyActionResult : ActionResult
{
readonly Func<ActionResult> _innerResult;
ActionResult _cachedResult;
public LazyActionResult(Func<ActionResult> innerResult)
{
if (innerResult == null) throw new ArgumentNullException("innerResult");
_innerResult = innerResult;
}
/// <summary>
/// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult"/> class.
/// </summary>
/// <param name="context">The context in which the result is executed. The context information includes the controller, HTTP content, request context, and route data.</param>
public override void ExecuteResult(ControllerContext context)
{
InnerResult.ExecuteResult(context);
}
internal ActionResult InnerResult
{
get { return _cachedResult ?? (_cachedResult = _innerResult()); }
}
}
public class LazyUnwrapFormatter : MediaTypeFormatter
{
readonly MediaTypeFormatter _innerMediaTypeFormatter;
public LazyUnwrapFormatter(MediaTypeFormatter innerMediaTypeFormatter)
{
_innerMediaTypeFormatter = innerMediaTypeFormatter;
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return true;
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
var unwrappedValue = value;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Lazy<>))
{
unwrappedValue = type.GetProperty("Value").GetValue(value, null);
}
return _innerMediaTypeFormatter.WriteToStreamAsync(type, unwrappedValue, writeStream, content, transportContext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment