Skip to content

Instantly share code, notes, and snippets.

@miguelludert
Created December 28, 2016 19:37
Show Gist options
  • Save miguelludert/098e0aa2c00453e2d294a6219ba2b1c0 to your computer and use it in GitHub Desktop.
Save miguelludert/098e0aa2c00453e2d294a6219ba2b1c0 to your computer and use it in GitHub Desktop.
Minimal Dependency Injection
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ThinkingSites
{
public class Injection
{
private static Dictionary<Type, Func<object>> Registry = new Dictionary<Type, Func<object>>();
public static void Register<Tin,Tout>(Tout singleton = null)
where Tin : class
where Tout : class, new()
{
var tin = typeof(Tin);
var tout = typeof(Tout);
if (Registry.ContainsKey(typeof(Tin)))
{
throw new InvalidOperationException($"Type {tin.Name} has already been registered");
}
if (!tin.IsAssignableFrom(tout))
{
throw new InvalidOperationException($"Type {tout.Name} does not inherit from type {tin.Name}");
}
Func<object> func;
if (singleton == null)
{
func = () => new Tout();
}
else
{
func = () => singleton;
}
Registry.Add(typeof(Tin), func);
}
public static Tout Get<Tout>() where Tout : class
{
if (Registry.ContainsKey(typeof(Tout)))
{
return (Tout)Registry[typeof(Tout)]();
} else
{
throw new InvalidOperationException($"Type {typeof(Tout).Name} has not been registered");
}
}
public static void Reset<Tout>()
{
Registry.Remove(typeof(Tout));
}
public static void ResetAll()
{
Registry.Clear();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment