Skip to content

Instantly share code, notes, and snippets.

@TCGV
Created December 4, 2018 15:03
Show Gist options
  • Save TCGV/e30aa964227ba0cd494bb1b6789226c8 to your computer and use it in GitHub Desktop.
Save TCGV/e30aa964227ba0cd494bb1b6789226c8 to your computer and use it in GitHub Desktop.
Simple dependency injection class
using System;
using System.Collections.Generic;
namespace Tcgv
{
public static class Injector
{
static Injector()
{
allocators = new Dictionary<Type, Func<object[], object>>();
}
public static void Register<T>(Func<T> alloc) where T : class
{
var key = typeof(T);
if (allocators.ContainsKey(key))
allocators.Remove(key);
allocators.Add(key, (args) => alloc());
}
public static void Register<T>(Func<object[], T> alloc) where T : class
{
var key = typeof(T);
if (allocators.ContainsKey(key))
allocators.Remove(key);
allocators.Add(key, (args) => alloc(args));
}
public static T Resolve<T>() where T : class
{
return (T)GetFunc<T>()(null);
}
public static T Resolve<T>(params object[] args)
{
return (T)GetFunc<T>()(args);
}
public static bool Exists<T>() where T : class
{
var key = typeof(T);
return allocators.ContainsKey(key);
}
private static Func<object[], object> GetFunc<T>()
{
var key = typeof(T);
if (!allocators.ContainsKey(key))
throw new KeyNotFoundException(key.Name);
return allocators[key];
}
private static Dictionary<Type, Func<object[], object>> allocators;
}
}
@TCGV
Copy link
Author

TCGV commented Dec 4, 2018

Sample usage for transient lifetime:

Injector.Register<IFoo>(() => new Foo());

/*
 .
 .
 */

var foo = Injector.Resolve<IFoo>();

And for singleton lifetime:

var singletonFoo = new Foo();
Injector.Register<IFoo>(() => singletonFoo);

/*
 .
 .
 */

var foo = Injector.Resolve<IFoo>();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment