├── .gitattributes ├── .gitignore ├── Core.meta ├── Core ├── Abstractions.meta ├── Abstractions │ ├── IDependenciesProvider.cs │ └── IDependenciesProvider.cs.meta ├── Attributes.meta ├── Attributes │ ├── InjectAttribute.cs │ ├── InjectAttribute.cs.meta │ ├── InjectRegionAttribute.cs │ ├── InjectRegionAttribute.cs.meta │ ├── ProvideAttribute.cs │ └── ProvideAttribute.cs.meta ├── Exceptions.meta ├── Exceptions │ ├── IndieProvideException.cs │ ├── IndieProvideException.cs.meta │ ├── IndieResolveException.cs │ └── IndieResolveException.cs.meta ├── Flags.meta ├── Flags │ ├── InjectRegion.cs │ └── InjectRegion.cs.meta ├── Indie.cs ├── Indie.cs.meta ├── IndieInjector.cs ├── IndieInjector.cs.meta ├── InjectFabric.cs ├── InjectFabric.cs.meta ├── Registration.meta └── Registration │ ├── DependenciesContainer.cs │ ├── DependenciesContainer.cs.meta │ ├── Dependency.cs │ └── Dependency.cs.meta ├── Editor.meta ├── Editor ├── IndieInjectorEditor.cs ├── IndieInjectorEditor.cs.meta ├── SceneDependenciesRootEditor.cs └── SceneDependenciesRootEditor.cs.meta ├── LICENSE ├── LICENSE.meta ├── README.md ├── README.md.meta ├── Usage.meta └── Usage ├── CoreDependenciesRoot.cs ├── CoreDependenciesRoot.cs.meta ├── MonoProvider.cs ├── MonoProvider.cs.meta ├── SceneAutoInjector.cs ├── SceneAutoInjector.cs.meta ├── SceneDependenciesRoot.cs └── SceneDependenciesRoot.cs.meta /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .DS_Store 3 | IndieInject/**/*.meta 4 | -------------------------------------------------------------------------------- /Core.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 3f7a32e63b7f4df2a929e87d2236698a 3 | timeCreated: 1719848960 -------------------------------------------------------------------------------- /Core/Abstractions.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 4313d07b4c4fc344cb649e4572528e37 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Core/Abstractions/IDependenciesProvider.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | namespace IndieInject 18 | { 19 | public interface IDependenciesProvider { } 20 | } -------------------------------------------------------------------------------- /Core/Abstractions/IDependenciesProvider.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f9b76656a7a6a2c41814852095125b71 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Core/Attributes.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: cbdcbd74c0fb0cb4490368e6a0dd1681 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Core/Attributes/InjectAttribute.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using System; 18 | using UnityEngine; 19 | 20 | namespace IndieInject 21 | { 22 | [HelpURL("https://github.com/RimuruDev/IndieInject")] 23 | [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property)] 24 | public sealed class InjectAttribute : Attribute 25 | { 26 | } 27 | } -------------------------------------------------------------------------------- /Core/Attributes/InjectAttribute.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 6d19aed51dcd1ff4f93534c50cc4f2c4 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Core/Attributes/InjectRegionAttribute.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using System; 18 | 19 | namespace IndieInject 20 | { 21 | [AttributeUsage(AttributeTargets.Class)] 22 | public sealed class InjectRegionAttribute : Attribute 23 | { 24 | public InjectRegion Region; 25 | 26 | public InjectRegionAttribute(InjectRegion region) 27 | { 28 | Region = region; 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /Core/Attributes/InjectRegionAttribute.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 94dd0305bab64c18805824e474e95222 3 | timeCreated: 1719562101 -------------------------------------------------------------------------------- /Core/Attributes/ProvideAttribute.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using System; 18 | using UnityEngine; 19 | 20 | namespace IndieInject 21 | { 22 | [HelpURL("https://github.com/RimuruDev/IndieInject")] 23 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] 24 | public sealed class ProvideAttribute : Attribute 25 | { 26 | public bool IsSingleton; 27 | 28 | public ProvideAttribute(bool isSingleton) 29 | { 30 | IsSingleton = isSingleton; 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Core/Attributes/ProvideAttribute.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 9eff16267c893604fb2aa10b0a8e8e67 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Core/Exceptions.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 6c0864b9d0f927444a6be56c75320823 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Core/Exceptions/IndieProvideException.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using System; 18 | using UnityEngine; 19 | 20 | namespace IndieInject 21 | { 22 | [HelpURL("https://github.com/RimuruDev/IndieInject")] 23 | public sealed class IndieProvideException : Exception 24 | { 25 | public IndieProvideException() : base() 26 | { 27 | } 28 | 29 | public IndieProvideException(string message) : base(message) 30 | { 31 | } 32 | 33 | public IndieProvideException(string message, Exception innerException) : base(message, innerException) 34 | { 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Core/Exceptions/IndieProvideException.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 4a96fbe0242412d4c97cefb3675c55e6 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Core/Exceptions/IndieResolveException.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using System; 18 | using UnityEngine; 19 | 20 | namespace IndieInject 21 | { 22 | [HelpURL("https://github.com/RimuruDev/IndieInject")] 23 | public sealed class IndieResolveException : Exception 24 | { 25 | public IndieResolveException() : base() 26 | { 27 | } 28 | 29 | public IndieResolveException(string message) : base(message) 30 | { 31 | } 32 | 33 | public IndieResolveException(string message, Exception innerException) : base(message, innerException) 34 | { 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Core/Exceptions/IndieResolveException.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: d460ac49568915b4b993c05f36062acc 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Core/Flags.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 216a81f45f84c754d99d4d97850a0317 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Core/Flags/InjectRegion.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using System; 18 | 19 | namespace IndieInject 20 | { 21 | [Flags] 22 | public enum InjectRegion 23 | { 24 | Fields = 1, 25 | Properties = 2, 26 | Methods = 4, 27 | All = Fields | Properties | Methods 28 | } 29 | } -------------------------------------------------------------------------------- /Core/Flags/InjectRegion.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 782b3c00503c0e94baf37a1a811e5b65 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Core/Indie.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | namespace IndieInject 18 | { 19 | public static class Indie 20 | { 21 | public static readonly IndieInjector Injector = new IndieInjector(); 22 | public static readonly InjectFabric Fabric = new InjectFabric(); 23 | } 24 | } -------------------------------------------------------------------------------- /Core/Indie.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 056c4fd2050641b6bb59dbd65ecbe3cf 3 | timeCreated: 1719912042 -------------------------------------------------------------------------------- /Core/IndieInjector.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using System; 18 | using UnityEngine; 19 | using System.Reflection; 20 | using System.Collections.Generic; 21 | using UnityEngine.SceneManagement; 22 | 23 | namespace IndieInject 24 | { 25 | public sealed class IndieInjector 26 | { 27 | private const BindingFlags BindingFlags = 28 | System.Reflection.BindingFlags.Instance | 29 | System.Reflection.BindingFlags.Public | 30 | System.Reflection.BindingFlags.NonPublic; 31 | 32 | private readonly DependenciesContainer coreContainer = new(); 33 | private DependenciesContainer sceneContainer; 34 | 35 | public IndieInjector() 36 | { 37 | SceneManager.sceneUnloaded += ClearSceneDependenciesContainer; 38 | } 39 | 40 | private void ClearSceneDependenciesContainer(Scene _) 41 | { 42 | sceneContainer?.Dispose(); 43 | sceneContainer = null; 44 | } 45 | 46 | #region Registration 47 | public void RegisterDependenciesToCore(CoreDependenciesRoot root) 48 | { 49 | var providers 50 | = root.transform.GetComponentsInChildren(); 51 | 52 | Register(providers, coreContainer); 53 | } 54 | 55 | public void RegisterSceneDependencies(SceneDependenciesRoot root) 56 | { 57 | sceneContainer = new DependenciesContainer(); 58 | 59 | var providers = root.transform.GetComponentsInChildren(); 60 | 61 | foreach (var provider in providers) 62 | { 63 | Indie.Injector.Inject(provider); 64 | } 65 | 66 | Register(providers, sceneContainer); 67 | } 68 | 69 | private void Register(IDependenciesProvider[] providers, DependenciesContainer container) 70 | { 71 | foreach (var provider in providers) 72 | { 73 | var methods = provider.GetType().GetMethods(BindingFlags); 74 | 75 | foreach (var method in methods) 76 | { 77 | if (!Attribute.IsDefined(method, typeof(ProvideAttribute))) 78 | { 79 | continue; 80 | } 81 | 82 | RegisterDependency(method, provider); 83 | } 84 | } 85 | 86 | void RegisterDependency(MethodInfo method, IDependenciesProvider provider) 87 | { 88 | Type dependencyType = method.ReturnType; 89 | 90 | bool isSingleton = ((ProvideAttribute) Attribute.GetCustomAttribute(method, typeof(ProvideAttribute))).IsSingleton; 91 | 92 | Func fabric 93 | = (Func) method.CreateDelegate(typeof(Func), provider); 94 | 95 | var dependencyRegistration = new Dependency(dependencyType, fabric, isSingleton); 96 | 97 | container.Add(dependencyType, dependencyRegistration); 98 | 99 | #if UNITY_EDITOR 100 | if (method.ReturnType.IsSubclassOf(typeof(Component)) || method.ReturnType == typeof(GameObject)) 101 | { 102 | Debug.LogWarning($"It's not recommended to store instances of GameObject or MonoBehaviour with DI({method.ReturnType} in {provider})." + 103 | $" If you want to store prefabs, use special containers"); 104 | } 105 | #endif 106 | } 107 | 108 | container.SetupSingletons(); 109 | } 110 | 111 | #endregion 112 | 113 | #region Inject 114 | 115 | public void Inject(object toInject) 116 | { 117 | var type = toInject.GetType(); 118 | 119 | //if it is gameobject so we need to inject in all his components not in it 120 | if (TryInjectInGameObject(toInject)) 121 | return; 122 | 123 | InjectRegion region = InjectRegion.All; 124 | 125 | var customAttribute = (InjectRegionAttribute)toInject.GetType().GetCustomAttribute(typeof(InjectRegionAttribute)); 126 | 127 | if (customAttribute != null) 128 | { 129 | region = customAttribute.Region; 130 | } 131 | 132 | //methods 133 | if((region & InjectRegion.Methods) == InjectRegion.Methods) 134 | { 135 | var allMethods = type.GetMethods(BindingFlags); 136 | 137 | foreach (var info in allMethods) 138 | { 139 | foreach (var attribute in info.GetCustomAttributes()) 140 | { 141 | if (attribute is not InjectAttribute) continue; 142 | 143 | var requiredParameters = info.GetParameters(); 144 | 145 | List parameters = new List(); 146 | 147 | foreach (var parameter in requiredParameters) 148 | { 149 | parameters.Add(Find(parameter.ParameterType).GetInstance()); 150 | } 151 | 152 | info.Invoke(toInject, parameters.ToArray()); 153 | } 154 | } 155 | } 156 | 157 | //fields 158 | if((region & InjectRegion.Fields) == InjectRegion.Fields) 159 | { 160 | var allFields = type.GetFields(BindingFlags); 161 | 162 | foreach (var info in allFields) 163 | { 164 | foreach (var attribute in info.GetCustomAttributes()) 165 | { 166 | if (attribute is not InjectAttribute) continue; 167 | 168 | info.SetValue(toInject, Find(info.FieldType).GetInstance()); 169 | } 170 | } 171 | } 172 | 173 | //properties 174 | if((region & InjectRegion.Properties) == InjectRegion.Properties) 175 | { 176 | var allProperties = type.GetProperties(BindingFlags); 177 | 178 | foreach (var info in allProperties) 179 | { 180 | foreach (var attribute in info.GetCustomAttributes()) 181 | { 182 | if (attribute is not InjectAttribute) continue; 183 | 184 | info.SetValue(toInject, Find(info.PropertyType).GetInstance()); 185 | } 186 | } 187 | } 188 | } 189 | 190 | private bool TryInjectInGameObject(object toInject) 191 | { 192 | if (toInject is GameObject gameObject) 193 | { 194 | var allMonoBehaviours = gameObject.GetComponentsInChildren(true); 195 | 196 | foreach (var monoBehaviour in allMonoBehaviours) 197 | { 198 | Inject(monoBehaviour); 199 | } 200 | 201 | return true; 202 | } 203 | 204 | return false; 205 | } 206 | 207 | private Dependency Find(Type type) 208 | { 209 | if (coreContainer.Get(type) != null) 210 | { 211 | return coreContainer.Get(type); 212 | } 213 | if (sceneContainer.Get(type) != null) 214 | { 215 | return sceneContainer.Get(type); 216 | } 217 | 218 | throw new IndieResolveException($"There is no dependency of type {type}"); 219 | } 220 | 221 | #endregion 222 | } 223 | } -------------------------------------------------------------------------------- /Core/IndieInjector.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 3e1fa34ae49c7424a951007e438462e6 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Core/InjectFabric.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using System; 18 | using UnityEngine; 19 | using Object = UnityEngine.Object; 20 | 21 | namespace IndieInject 22 | { 23 | public sealed class InjectFabric 24 | { 25 | public event Action OnInstantiated; 26 | public event Action OnGameObjectInstantiated; 27 | 28 | public TObject Instantiate(TObject original, Vector3 position) 29 | where TObject : Object 30 | { 31 | return Instantiate(original, position, Quaternion.identity, null); 32 | } 33 | 34 | public TObject Instantiate(TObject original, Transform transform) 35 | where TObject : Object 36 | { 37 | return Instantiate(original, transform.position, Quaternion.identity, transform); 38 | } 39 | 40 | 41 | public TObject Instantiate(TObject original, Vector3 position, Transform parent) 42 | where TObject : Object 43 | { 44 | return Instantiate(original, position, Quaternion.identity, parent); 45 | } 46 | 47 | public TObject Instantiate(TObject original, Vector3 position, Quaternion rotation) 48 | where TObject : MonoBehaviour 49 | { 50 | return Instantiate(original, position, rotation, null); 51 | } 52 | 53 | public TObject Instantiate(TObject original, Vector3 position, Quaternion rotation, 54 | Transform parent) 55 | where TObject : Object 56 | { 57 | var instance = Object.Instantiate(original, position, rotation, parent); 58 | 59 | Indie.Injector.Inject(instance); 60 | 61 | OnInstantiated?.Invoke(instance); 62 | InvokeGameObjectEventsIfGameObject(); 63 | 64 | return instance; 65 | 66 | void InvokeGameObjectEventsIfGameObject() 67 | { 68 | if (instance is GameObject gameObject) 69 | { 70 | OnGameObjectInstantiated?.Invoke(gameObject); 71 | } 72 | else if (instance is Component component) 73 | { 74 | OnGameObjectInstantiated?.Invoke(component.gameObject); 75 | } 76 | } 77 | } 78 | } 79 | } -------------------------------------------------------------------------------- /Core/InjectFabric.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 40adc7110f6f4f8893bb42184d713129 3 | timeCreated: 1719912488 -------------------------------------------------------------------------------- /Core/Registration.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: d7af53ac98794bd98e8c02e5f675b59b 3 | timeCreated: 1719564430 -------------------------------------------------------------------------------- /Core/Registration/DependenciesContainer.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using System; 18 | using System.Collections.Generic; 19 | using UnityEngine; 20 | 21 | namespace IndieInject 22 | { 23 | public sealed class DependenciesContainer : IDisposable 24 | { 25 | private readonly Dictionary dependencies = new (); 26 | 27 | public void Dispose() 28 | { 29 | foreach (var dependencyPair in dependencies) 30 | { 31 | dependencyPair.Value.Dispose(); 32 | } 33 | } 34 | 35 | public Dependency Get() 36 | { 37 | return dependencies[typeof(TDependency)]; 38 | } 39 | 40 | public Dependency Get(Type type) 41 | { 42 | if (dependencies.TryGetValue(type, out var dependency)) 43 | { 44 | return dependency; 45 | } 46 | 47 | return null; 48 | } 49 | 50 | public void Add(Type dependencyType, Dependency dependency) 51 | { 52 | if (!dependencies.TryAdd(dependencyType, dependency)) 53 | { 54 | #if UNITY_EDITOR 55 | Debug.LogWarning($"{dependencyType} DEPENDENCY ALREADY REGISTERED"); 56 | #endif 57 | } 58 | } 59 | 60 | public void Remove() 61 | { 62 | if (dependencies.ContainsKey(typeof(TDependency))) 63 | dependencies.Remove(typeof(TDependency)); 64 | } 65 | 66 | public void SetupSingletons() 67 | { 68 | foreach (var dependencyPair in dependencies) 69 | { 70 | if (dependencyPair.Value.IsSingleton) 71 | { 72 | Indie.Injector.Inject(dependencyPair.Value.GetInstance()); 73 | } 74 | } 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /Core/Registration/DependenciesContainer.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 628a089ed9ec4f049b4828ef7a7a35e3 3 | timeCreated: 1719246882 -------------------------------------------------------------------------------- /Core/Registration/Dependency.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using System; 18 | 19 | namespace IndieInject 20 | { 21 | public sealed class Dependency : IDisposable 22 | { 23 | public readonly Type Type; 24 | public readonly bool IsSingleton; 25 | 26 | private readonly Func fabric; 27 | private object instance; 28 | 29 | public Dependency(Type type, Func fabric, bool isSingleton) 30 | { 31 | Type = type; 32 | this.fabric = fabric; 33 | IsSingleton = isSingleton; 34 | } 35 | 36 | public void Dispose() 37 | { 38 | if (IsSingleton && instance is IDisposable disposable) 39 | { 40 | disposable.Dispose(); 41 | } 42 | } 43 | 44 | public object GetInstance() 45 | { 46 | if (IsSingleton && instance == null) 47 | { 48 | instance = fabric.Invoke(); 49 | } 50 | else if (IsSingleton) 51 | { 52 | if (instance == null) 53 | { 54 | throw new IndieProvideException($"Your provider of type {Type} returns null"); 55 | } 56 | 57 | return instance; 58 | } 59 | 60 | object newInstance = fabric.Invoke(); 61 | 62 | if(newInstance == null) 63 | { 64 | throw new IndieProvideException($"Your provider of {Type} provides null"); 65 | } 66 | 67 | return fabric.Invoke(); 68 | } 69 | } 70 | } -------------------------------------------------------------------------------- /Core/Registration/Dependency.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 04edf7e092874e19950f1e88d81fd4f0 3 | timeCreated: 1719247539 -------------------------------------------------------------------------------- /Editor.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: bba45264e4c84a27ad09aa5aeb76e9ba 3 | timeCreated: 1716754248 -------------------------------------------------------------------------------- /Editor/IndieInjectorEditor.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using UnityEditor; 18 | using UnityEngine; 19 | 20 | namespace IndieInject.Editor 21 | { 22 | [HelpURL("https://github.com/RimuruDev/IndieInject")] 23 | public static class IndieInjectorEditor 24 | { 25 | private const string RootName = "[ === Dependencies Root === ]"; 26 | private const string AutoInjectorName = "[ === Auto Injector === ]"; 27 | 28 | [InitializeOnLoadMethod] 29 | private static void OnProjectLoadedInEditor() 30 | { 31 | EditorApplication.playModeStateChanged += OnPlayModeStateChanged; 32 | } 33 | 34 | [MenuItem("IndieInject/Setup Scene")] 35 | public static void SetupSceneRoot() 36 | { 37 | if (Object.FindObjectOfType() == null) 38 | { 39 | var injectorObject = new GameObject(RootName); 40 | 41 | injectorObject.AddComponent(); 42 | 43 | Undo.RegisterCreatedObjectUndo(injectorObject, $"Create {RootName}"); 44 | 45 | EditorUtility.SetDirty(injectorObject); 46 | } 47 | else 48 | { 49 | Debug.LogWarning($"An {RootName} already exists in the scene. Only one instance is allowed."); 50 | } 51 | } 52 | 53 | [MenuItem("IndieInject/Setup Scene Auto Inject")] 54 | public static void SetupSceneAutoInject() 55 | { 56 | if (Object.FindObjectOfType(true)) 57 | { 58 | var autoInject = Object.FindObjectOfType(true); 59 | 60 | if (autoInject == null) 61 | { 62 | var injectorObject = new GameObject(AutoInjectorName); 63 | 64 | injectorObject.AddComponent(); 65 | 66 | Undo.RegisterCreatedObjectUndo(injectorObject, $"Create {AutoInjectorName}"); 67 | 68 | EditorUtility.SetDirty(injectorObject); 69 | } 70 | else 71 | { 72 | Debug.LogWarning("SceneAutoInjector has already been added to the scene."); 73 | } 74 | } 75 | else 76 | { 77 | Debug.LogWarning("No dependencies root in scene"); 78 | } 79 | } 80 | 81 | [MenuItem("IndieInject/Setup Entry Point")] 82 | public static void SetupCoreRoot() 83 | { 84 | if (Object.FindObjectOfType() == null) 85 | { 86 | var rootObject = new GameObject(RootName); 87 | 88 | rootObject.AddComponent(); 89 | 90 | Undo.RegisterCreatedObjectUndo(rootObject, $"Create {RootName}"); 91 | 92 | EditorUtility.SetDirty(rootObject); 93 | } 94 | else 95 | { 96 | Debug.LogWarning($"An {RootName} already exists in the scene. Only one instance is allowed."); 97 | } 98 | } 99 | 100 | [MenuItem("IndieInject/Clear")] 101 | public static void ClearIndieInjector() 102 | { 103 | { 104 | var coreRoot = Object.FindObjectOfType(); 105 | 106 | if (coreRoot != null) 107 | { 108 | Undo.DestroyObjectImmediate(coreRoot.gameObject); 109 | Debug.Log("Core Dependencies Root was deleted"); 110 | } 111 | } 112 | { 113 | var sceneRoot = Object.FindObjectOfType(); 114 | 115 | if (sceneRoot != null) 116 | { 117 | Undo.DestroyObjectImmediate(sceneRoot.gameObject); 118 | Debug.Log("Scene Dependencies Root was deleted"); 119 | } 120 | } 121 | } 122 | 123 | private static void OnPlayModeStateChanged(PlayModeStateChange state) 124 | { 125 | if (state == PlayModeStateChange.EnteredPlayMode) 126 | { 127 | EnsureSingleRoot(); 128 | } 129 | } 130 | 131 | private static void EnsureSingleRoot() 132 | { 133 | { 134 | var roots = Object.FindObjectsOfType(); 135 | 136 | if (roots.Length > 1) 137 | { 138 | Debug.LogWarning("More than one Core Root found. Keeping only the first one."); 139 | 140 | for (var i = 1; i < roots.Length; i++) 141 | { 142 | Object.DestroyImmediate(roots[i].gameObject); 143 | } 144 | } 145 | } 146 | { 147 | var roots = Object.FindObjectsOfType(); 148 | 149 | if (roots.Length > 1) 150 | { 151 | Debug.LogWarning("More than one Scene Root found. Keeping only the first one."); 152 | 153 | for (var i = 1; i < roots.Length; i++) 154 | { 155 | Object.DestroyImmediate(roots[i].gameObject); 156 | } 157 | } 158 | } 159 | } 160 | } 161 | } -------------------------------------------------------------------------------- /Editor/IndieInjectorEditor.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: dadd122b12cd41b28f285d171716ac8e 3 | timeCreated: 1716754474 -------------------------------------------------------------------------------- /Editor/SceneDependenciesRootEditor.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using UnityEditor; 18 | using UnityEngine; 19 | 20 | namespace IndieInject.Editor 21 | { 22 | [CustomEditor(typeof(SceneDependenciesRoot))] 23 | public class SceneDependenciesRootEditor : UnityEditor.Editor 24 | { 25 | public override void OnInspectorGUI() 26 | { 27 | var root = (SceneDependenciesRoot)target; 28 | 29 | EditorGUI.BeginChangeCheck(); 30 | 31 | var newEnableAutoInjector = (EnableAutoInjector)EditorGUILayout.EnumPopup("Enable Auto Injector", root.EnableAutoInjector); 32 | 33 | if (EditorGUI.EndChangeCheck()) 34 | { 35 | Undo.RecordObject(root, "Change Enable Auto Injector"); 36 | root.EnableAutoInjector = newEnableAutoInjector; 37 | EditorUtility.SetDirty(root); 38 | 39 | if (root.EnableAutoInjector == EnableAutoInjector.Enable) 40 | { 41 | if (root.GetComponent() == null) 42 | { 43 | var existingInjectors = FindObjectsOfType(true); 44 | 45 | if (existingInjectors.Length == 0) 46 | { 47 | root.gameObject.AddComponent(); 48 | Debug.Log("SceneAutoInjector added."); 49 | } 50 | else 51 | { 52 | Debug.LogWarning("SceneAutoInjector already exists in the scene. Cannot add another."); 53 | } 54 | } 55 | } 56 | else if (root.EnableAutoInjector == EnableAutoInjector.Disable) 57 | { 58 | var injector = root.GetComponent(); 59 | if (injector != null) 60 | { 61 | DestroyImmediate(injector); 62 | Debug.Log("SceneAutoInjector removed."); 63 | } 64 | } 65 | } 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /Editor/SceneDependenciesRootEditor.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: adbef362e4114cecb04ed44929fbbc9c 3 | timeCreated: 1720254079 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Rimuru 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LICENSE.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 521d6fe3a144b654190d630508d89870 3 | DefaultImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Описание 2 | 3 | IndieInject - легковесный DI фреймворк, который может спокойно использоваться в прототипах и в крупных проектах, благодаря тому, что его легко можно адаптировать под любую архитектуру. 4 | 5 | # Установка 6 | 1. Откройте Unity и перейдите в окно **Package Manager**: **Window** > **Package Manager**. 7 | 2. Нажмите на кнопку `+` в левом верхнем углу окна Package Manager и выберите **Add package from git URL...**. 8 | 3. Введите URL репозитория: `https://github.com/RimuruDev/IndieInject-Installer.git` и нажмите **Add**. 9 | 4. Unity автоматически скачает и установит пакет IndieInject Installer. 10 | 5. Если непонятно как пользоваться установщитам: [короткая документация](https://github.com/RimuruDev/IndieInject-Installer/blob/main/README.md). 11 | 12 | # Возможности 13 | 14 | - Core зависимости и Scene зависимости 15 | - Инъекция при помощи рефлексии в методы, поля, свойства 16 | - Регистрация зависимостей посредством создания фабрик из методов, которые отмечены Provide атрибутом 17 | - Singleton и Transient типы регистрации 18 | - Опциональная автоматическая инъекция в начальные объекты на сцене 19 | - Создание объектов с автоматической инъекцией, если создавать объекты через Indie.Fabric.Instantiate 20 | 21 | # Логика 22 | 23 | ### Хранение 24 | Зависимости **хранятся** в двух контейнерах: для Core зависимостей, которые будут существовать весь жизненный цикл игры и для сцен, которые очищаются сразу после отгрузки сцены. 25 | ### Регистрация 26 | **Регистрация** зависимостей происходит путем создания фабрик из методов в провайдере, которые обозначены атрибутом [Provide]. 27 | ### Типы выдачи 28 | Есть два **типа выдачи** зависимости: Singleton и Transient. Первый будет создавать зависимость при ее регистрации и выдавать всегда именно этот экземпляр. Второй будет создавать при каждой инъекции новый экземпляр. 29 | ### Инъекция 30 | **Инъецкция** реализована при помощи рефлексии. Можно делать инъекцию в поля, свойства, методы, которые обозначены атрибутом Inject. 31 | ### Как инициализируются зависимости 32 | После того, как происходит регистрация всех зависимостей из провайдеров, то идет инициалиация синглтонов и их инъекция. В Transient зависимости инъекция происходит, когда новый экземпляр создан. 33 | 34 | # API 35 | 36 | - IDependencyProvider - интерфейс, по которому передаются провайдеры для регистрации 37 | - [Provide(bool isSingleton)] - атрибут, который отображает, какой метод будет использован для регистрации, как фабрика зависимости 38 | - MonoProvider - MonoBehavior, который отнаследован от IDependecyProvider. Его можно использовать для всех провайдеров 39 | - Core/Scene Dependencies Root - они запускают регестрацию зависимостей. Все провайдеры должны быть расположены или как дочерние объекты для Root-а, либо на них 40 | - SceneAutoInjector - если находится на сцене, то будет сделана инъекция, во все находящиеся на сцене объекты 41 | - Indie.Injector.Inject() - инъекция в объект 42 | - Indie.Fabric.Instantiate() - аналог Object.Instantiate, но с автоматической инъекцией 43 | - Indie.Fabric.OnInstantiated - событие, которое вызывается при созднии объекта 44 | - Indie.Fabric.OnGameObjectInstantiated - событие, которое вызывается при созднии GameObject 45 | - [Inject] - показывает, в какой метод, поле, свойство нужно сделать инъекцию 46 | - [InjectRegion(InjectRegion region)] - атрибут, который добавляется к классу для того, чтобы показать, в какую область нужно делать инъекцию. Если атрибута нет, то будет инъекция во все 47 | 48 | # Как пользоваться 49 | 50 | Рассмотрим, как можно использовать Indie Inject на примере, который приведен в папке Sample. Его можно скачать отдельно в релизах 51 | 52 | Задачи: 53 | - Регистрация InputService-а, как Core зависимость 54 | - Регистрация префаба игрока, его рутового объекта, его конфига для конкретной сцены 55 | - Инъекция в фабрику, которая изначально находится на сцене 56 | - Создание игрока через фабрику и его инъекция 57 | 58 | ```cs 59 | [Inject] private GameObject playerPrefab; 60 | private Transform rootTransform; 61 | 62 | [Inject] 63 | private void Constructor(Transform rootTransformForSpawnHero) 64 | { 65 | rootTransform = rootTransformForSpawnHero; 66 | } 67 | ``` 68 | 69 | ```cs 70 | [Inject] private InputService InputService { get; set; } 71 | [Inject] private HeroConfig HeroConfig { get; set; } 72 | ``` 73 | 74 | Для начала, нам нужно создать Entry Point для примера. Создадим новую сцену и назовем ее, например, StartPoint. Теперь нам нужно создать Dependency Root для Core зависимостей. Для автоматизации их создания мы сделали специальное меню, которое называется IndieInject. Там нужно нажать Create Entry Point. Мы хотим регистрировать InputService, поэтому создадим класс InputServiceProvider и отнаследуемся от MonoProvider-а. 75 | 76 | ```cs 77 | public class InputServiceProvider : MonoProvider 78 | { 79 | [Provide(true)] 80 | public InputService ProvideInputService() => new(); 81 | } 82 | ``` 83 | 84 | В этом классе мы объвляем метод ProvideInputService(), который возвращает просто новый экземпляр InputService, чтобы этот метод был использован как фабрика, мы его обозначили атрибутом [Provide] и указали, что это синглтон. Добавим этот компонент на CoreDependenciesRoot, настройка Entry Point завершена. Теперь нам нужно сделать автоматический переход в SampeScene. 85 | 86 | Рассмотрим устройство фабрики игрока: 87 | ```cs 88 | public class HeroFactory : MonoBehaviour 89 | { 90 | // === Inject in field === // 91 | [Inject] private GameObject playerPrefab; 92 | private Transform rootTransform; 93 | 94 | // === Inject in method === // 95 | [Inject] 96 | private void Constructor(Transform rootTransformForSpawnHero) 97 | { 98 | rootTransform = rootTransformForSpawnHero; 99 | } 100 | 101 | private void Start() 102 | { 103 | // === Instantiate + Inject in new GameObject === // 104 | Indie.Fabric.Instantiate(playerPrefab, rootTransform); 105 | } 106 | } 107 | ``` 108 | 109 | В ней мы должны получить префаб игрока и родительского контейнера. На старте мы создаем игрока через Indie.Fabric.Instantiate() 110 | 111 | Рассмотрим игрока: 112 | ```cs 113 | public class Hero : MonoBehaviour 114 | { 115 | // === Inject in properties === // 116 | [Inject] private InputService InputService { get; set; } 117 | [Inject] private HeroConfig HeroConfig { get; set; } 118 | 119 | private Rigidbody heroRigidbody; 120 | 121 | private void Awake() => heroRigidbody = GetComponent(); 122 | 123 | private void Update() { /*movement*/ } 124 | } 125 | ``` 126 | В нем нам нужно получать InputService и HeroConfig. InputService мы уже зарегестрировали как Core зависимость. Теперь осталось зарегистрировать оставшиеся. 127 | 128 | ```cs 129 | public sealed class HeroDataProvider : MonoProvider 130 | { 131 | [SerializeField] private GameObject playerPrefab; 132 | [SerializeField] private Transform rootTransformForHero; 133 | [SerializeField] private HeroConfig heroConfig; 134 | 135 | [Provide(true)] 136 | public GameObject ProvidePlayerPrefab() => playerPrefab; 137 | 138 | [Provide(true)] 139 | public HeroConfig ProvidePlayerConfig() => heroConfig; 140 | 141 | [Provide(true)] 142 | public Transform RootTransformForHero() => rootTransformForHero; 143 | 144 | private void OnValidate() { /*getting data from resources*/ } 145 | } 146 | ``` 147 | Чтобы быстро создать SceneDependenciesRoot воспользуемся кнопкой Setup Scene в меню IndieInject. Добавим дочерний объект с компонентом HeroDataProvider и все! 148 | 149 | # Support 150 | [Telegram chat](https://t.me/+oreXCzmtsjc5YWFi) 151 | -------------------------------------------------------------------------------- /README.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 21e0ac3086dedcf429bbb9852d613d1b 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Usage.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: c6fdbcc515004b1eabb7945b788f48ef 3 | timeCreated: 1719558234 -------------------------------------------------------------------------------- /Usage/CoreDependenciesRoot.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using UnityEngine; 18 | 19 | namespace IndieInject 20 | { 21 | [DefaultExecutionOrder(-999)] 22 | public sealed class CoreDependenciesRoot : MonoBehaviour 23 | { 24 | private void Awake() 25 | { 26 | Indie.Injector.RegisterDependenciesToCore(this); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Usage/CoreDependenciesRoot.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 014a0677fd974d439c9e6cc90d156a0d 3 | timeCreated: 1719913895 -------------------------------------------------------------------------------- /Usage/MonoProvider.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using UnityEngine; 18 | 19 | namespace IndieInject 20 | { 21 | [HelpURL("https://github.com/RimuruDev/IndieInject")] 22 | public abstract class MonoProvider : MonoBehaviour, IDependenciesProvider 23 | { 24 | } 25 | } -------------------------------------------------------------------------------- /Usage/MonoProvider.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 6c1d4fcbd9954fc59333b9e9f30f96f2 3 | timeCreated: 1719915262 -------------------------------------------------------------------------------- /Usage/SceneAutoInjector.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using UnityEngine; 18 | 19 | namespace IndieInject 20 | { 21 | [DefaultExecutionOrder(-300)] 22 | public sealed class SceneAutoInjector : MonoBehaviour 23 | { 24 | private void Awake() 25 | { 26 | var all = FindObjectsOfType(true); 27 | 28 | foreach (var monoBehaviour in all) 29 | { 30 | Indie.Injector.Inject(monoBehaviour); 31 | } 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Usage/SceneAutoInjector.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 956e53024dae415ba195043b95aee43b 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: -300 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Usage/SceneDependenciesRoot.cs: -------------------------------------------------------------------------------- 1 | // **************************************************************** // 2 | // 3 | // Copyright (c) RimuruDev, YUJECK. All rights reserved. 4 | // Contact us: 5 | // - RimuruDev: 6 | // - Gmail: rimuru.dev@gmail.com 7 | // - LinkedIn: https://www.linkedin.com/in/rimuru/ 8 | // - GitHub: https://github.com/RimuruDev 9 | // - YUJECK: 10 | // - GitHub: https://github.com/YUJECK 11 | // 12 | // This project is licensed under the MIT License. 13 | // See the LICENSE file in the project root for more information. 14 | // 15 | // **************************************************************** // 16 | 17 | using UnityEngine; 18 | 19 | namespace IndieInject 20 | { 21 | public enum EnableAutoInjector : byte 22 | { 23 | Enable = 0, 24 | Disable = 1, 25 | } 26 | 27 | [DefaultExecutionOrder(-500)] 28 | public sealed class SceneDependenciesRoot : MonoBehaviour 29 | { 30 | #if UNITY_EDITOR 31 | public EnableAutoInjector EnableAutoInjector; 32 | #endif 33 | 34 | private void Awake() 35 | { 36 | Indie.Injector.RegisterSceneDependencies(this); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /Usage/SceneDependenciesRoot.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: db839343cc98964478162de840011b3b 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: -500 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | --------------------------------------------------------------------------------