Created
August 3, 2011 19:20
-
-
Save crfilho/1123542 to your computer and use it in GitHub Desktop.
Simple Container
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
public class Container | |
{ | |
private static readonly IDictionary<Type, object> components = new Dictionary<Type, object>(); | |
public static T Resolve<T>() where T : class, new() | |
{ | |
if (typeof(ITransient).IsAssignableFrom(typeof(T))) | |
return new T(); | |
if (!components.ContainsKey(typeof(T))) | |
{ | |
components.Add(typeof(T), new T()); | |
} | |
return components[typeof(T)] as T; | |
} | |
public static void Register<T>(T component) | |
{ | |
if (components.ContainsKey(typeof(T))) | |
components[typeof(T)] = component; | |
else | |
components.Add(typeof(T), component); | |
} | |
public static T Lookup<T>() where T : class | |
{ | |
if (components.ContainsKey(typeof(T))) | |
{ | |
return components[typeof(T)] as T; | |
} | |
return default(T); | |
} | |
public static void Release<T>() | |
{ | |
if (components.ContainsKey(typeof(T))) | |
{ | |
components[typeof(T)] = null; | |
} | |
} | |
public static void ReleaseComponents() | |
{ | |
foreach (KeyValuePair<Type,object> c in components) | |
{ | |
Type t = c.Value.GetType(); | |
if (typeof(IDisposable).IsAssignableFrom(t)) | |
{ | |
((IDisposable)c.Value).Dispose(); | |
} | |
} | |
} | |
} | |
public interface ITransient { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment