Created
February 19, 2019 19:08
-
-
Save marijnz/2907ab9de26a32fe41dbae009ef22262 to your computer and use it in GitHub Desktop.
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; | |
using Assets.Scripts.Core; | |
using UnityEngine; | |
using Object = UnityEngine.Object; | |
public class Inject : Attribute { } | |
public class Controller | |
{ | |
public Controller() | |
{ | |
Injector.Inject(this); | |
Updater.Add(this); | |
} | |
} | |
public class Injector | |
{ | |
static Dictionary<Type, object> objects = new Dictionary<Type, object>(); | |
public static T Get<T>() | |
{ | |
return (T) Get(typeof(T)); | |
} | |
static object Get(Type type) | |
{ | |
object obj; | |
objects.TryGetValue(type, out obj); | |
if(obj == null) | |
{ | |
if(typeof(Object).IsAssignableFrom(type)) | |
{ | |
obj = Object.FindObjectOfType(type); | |
Debug.Assert(obj != null, "Couldn't find view for " +type); | |
} | |
else | |
{ | |
obj = Activator.CreateInstance(type); | |
} | |
objects[type] = obj; | |
} | |
return obj; | |
} | |
public static void Inject(object obj) | |
{ | |
foreach (var field in obj.GetType().GetFieldsWithAttribute<Inject>()) | |
{ | |
var fieldObj = Get(field.FieldType); | |
field.SetValue(obj, fieldObj); | |
} | |
} | |
public static void Clear() | |
{ | |
objects.Clear(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment