Created
December 4, 2018 15:03
-
-
Save TCGV/e30aa964227ba0cd494bb1b6789226c8 to your computer and use it in GitHub Desktop.
Simple dependency injection class
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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage for transient lifetime:
And for singleton lifetime: