private static bool FindTypeInjections(Type t, out TypeInjections result) { result = new TypeInjections(); using (var fields = ListPool <FieldInfo> .Get()) using (var injectFields = ListPool <FieldInfo> .Get()) { t.GetFieldsIncludingBaseTypes(fields, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (var f in fields) { var fAttrs = f.GetCustomAttributes(true); foreach (var a in fAttrs) { if (!typeof(InjectAttribute).IsAssignableFrom(a.GetType())) { continue; } injectFields.Add(f); } } result.fields = injectFields.Count > 0 ? injectFields.ToArray() : EMPTY_FIELDS; } using (var props = ListPool <PropertyInfo> .Get()) using (var injectProps = ListPool <PropertyInfo> .Get()) { t.GetPropertiesIncludingBaseTypes(props, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (var p in props) { var pAttrs = p.GetCustomAttributes(true); foreach (var a in pAttrs) { if (!typeof(InjectAttribute).IsAssignableFrom(a.GetType())) { continue; } injectProps.Add(p); } } result.properties = injectProps.Count > 0 ? injectProps.ToArray() : EMPTY_PROPS; } return(result.fields.Length > 0 || result.properties.Length > 0); }
public static bool On(object instance) { var instType = instance.GetType(); TypeInjections typeInjections = GetTypeInjections(instType); var eventHandler = instance as DependencyInjectionEventHandler; var willInjectEventSent = false; if (typeInjections.fields != null && typeInjections.fields.Length > 0) { foreach (var f in typeInjections.fields) { if (f.GetValue(instance) != null) { // don't overwrite if already set continue; } if (!(Services.exists && Services.Get.hasInit)) { InjectOnServicesInit(instance); return(false); } if (eventHandler != null && !willInjectEventSent) { eventHandler.OnWillInjectDependencies(); willInjectEventSent = true; } var v = Services.Get.GetService(f.FieldType); if (v == null) { #if UNITY_EDITOR || DEBUG_UNSTRIP Debug.LogError("[" + Time.frameCount + "] service not registered for type " + f.FieldType + " marked for injection by type " + instType); #endif continue; } f.SetValue(instance, v); } } if (typeInjections.properties != null && typeInjections.properties.Length > 0) { foreach (var p in typeInjections.properties) { if (p.GetValue(instance, null) != null) { // don't overwrite if already set continue; } if (!(Services.exists && Services.Get.hasInit)) { InjectOnServicesInit(instance); return(false); } if (eventHandler != null && !willInjectEventSent) { eventHandler.OnWillInjectDependencies(); willInjectEventSent = true; } var v = Services.Get.GetService(p.PropertyType); if (v == null) { #if UNITY_EDITOR || DEBUG_UNSTRIP Debug.LogError("[" + Time.frameCount + "] service not registered for type " + p.PropertyType + " marked for injection by type " + instType); #endif continue; } p.SetValue(instance, v, null); } } if (eventHandler != null) { eventHandler.OnDidInjectDependencies(); } return(true); }