Created
April 24, 2014 01:52
-
-
Save shaunol/11238848 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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