Skip to content

Instantly share code, notes, and snippets.

@marijnz
Created March 6, 2019 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marijnz/9a048b6c37d3cb7daa63d167eac6d829 to your computer and use it in GitHub Desktop.
Save marijnz/9a048b6c37d3cb7daa63d167eac6d829 to your computer and use it in GitHub Desktop.
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