Skip to content

Instantly share code, notes, and snippets.

@crfilho
Created August 3, 2011 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save crfilho/1123542 to your computer and use it in GitHub Desktop.
Save crfilho/1123542 to your computer and use it in GitHub Desktop.
Simple Container
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