Skip to content

Instantly share code, notes, and snippets.

@shaunol
Created April 24, 2014 01:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaunol/11238848 to your computer and use it in GitHub Desktop.
Save shaunol/11238848 to your computer and use it in GitHub Desktop.
internal class OwinContextLifetimeProvider : TinyIoCContainer.ITinyIoCObjectLifetimeProvider
{
/// <summary>
/// Prefix to use on HttpContext items
/// </summary>
private const string PREFIX = "TinyIoC.OwinContext.";
/// <summary>
/// Name of the key for this particular registration
/// </summary>
private readonly string _keyName = PREFIX + Guid.NewGuid();
private static IOwinContext _Context;
public OwinContextLifetimeProvider(IOwinContext context)
{
_Context = context;
}
/// <summary>
/// Gets the stored object if it exists, or null if not
/// </summary>
/// <returns>Object instance or null</returns>
public object GetObject()
{
object obj;
_Context.Environment.TryGetValue(_keyName, out obj);
return obj;
}
/// <summary>
/// Store the object
/// </summary>
/// <param name="value">Object to store</param>
public void SetObject(object value)
{
_Context.Set(_keyName, value);
}
/// <summary>
/// Release the object
/// </summary>
public void ReleaseObject()
{
var item = GetObject() as IDisposable;
if (item != null)
item.Dispose();
SetObject(null);
}
/// <summary>
/// Disposes all instantiated components
/// </summary>
public static void DisposeAll()
{
var items = _Context.Environment;
var disposableItems = items.Keys.OfType<string>()
.Where(key => key.StartsWith(PREFIX))
.Select(key => items[key])
.Where(item => item is IDisposable);
foreach (var item in disposableItems)
{
((IDisposable)item).Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment