├── Src ├── dlls │ └── UnityEngine.dll ├── ResolveSubset.cs ├── ResolveScene.cs ├── InjectAttribute.cs ├── Properties │ └── AssemblyInfo.cs ├── Unity-Dependency-Injection.csproj └── DependencyResolver.cs ├── README.md ├── Unity-Dependency-Injection.sln ├── LICENSE ├── .gitattributes └── .gitignore /Src/dlls/UnityEngine.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Real-Serious-Games/Unity-Dependency-Injection/HEAD/Src/dlls/UnityEngine.dll -------------------------------------------------------------------------------- /Src/ResolveSubset.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | /// 5 | /// Resolves dependencies only for the game object that it is attached to (and all its children). 6 | /// 7 | public class ResolveSubset : MonoBehaviour 8 | { 9 | /// 10 | /// Resolve subset dependencies on awake. 11 | /// 12 | void Awake() 13 | { 14 | var dependencyResolver = new DependencyResolver(); 15 | dependencyResolver.Resolve(this.gameObject); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Unity-Dependency-Injection 2 | 3 | A simple scene-based dependency injection system for Unity. 4 | 5 | A series of articles on DI for Unity has been published on [What Could Possibly Go Wrong](http://www.what-could-possibly-go-wrong.com/dependency-injection-for-unity-part-1/?utm_source=ash&utm_medium=github&utm_campaign=dependency-injection). 6 | 7 | Example Unity project can be found here: [https://github.com/Real-Serious-Games/Unity-Dependency-Injection](https://github.com/Real-Serious-Games/Unity-Dependency-Injection-Example). 8 | -------------------------------------------------------------------------------- /Src/ResolveScene.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | using UnityEngine.SceneManagement; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Reflection; 7 | using System; 8 | 9 | /// 10 | /// Resolves dependencies for the entire scene. 11 | /// 12 | public class ResolveScene : MonoBehaviour 13 | { 14 | /// 15 | /// Resolve scene dependencies on awake. 16 | /// 17 | void Awake() 18 | { 19 | var dependencyResolver = new DependencyResolver(); 20 | dependencyResolver.ResolveScene(); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Src/InjectAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public enum InjectFrom 4 | { 5 | /// 6 | /// Inject from the hierarchy above the current game object. 7 | /// 8 | Above, 9 | 10 | /// 11 | /// Inject from anywhere in the scene. 12 | /// 13 | Anywhere 14 | } 15 | 16 | /// 17 | /// Attribute that indentifies dependencies to be injected, aka injection points. 18 | /// 19 | public class InjectAttribute : Attribute 20 | { 21 | /// 22 | /// Indentifies where the dependency can be injected from. 23 | /// 24 | public InjectFrom InjectFrom { get; private set; } 25 | 26 | public InjectAttribute(InjectFrom injectFrom) 27 | { 28 | this.InjectFrom = injectFrom; 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Unity-Dependency-Injection.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25123.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Unity-Dependency-Injection", "Src\Unity-Dependency-Injection.csproj", "{E872AA21-9BD1-4B59-9459-2632327D3D4F}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {E872AA21-9BD1-4B59-9459-2632327D3D4F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {E872AA21-9BD1-4B59-9459-2632327D3D4F}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {E872AA21-9BD1-4B59-9459-2632327D3D4F}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {E872AA21-9BD1-4B59-9459-2632327D3D4F}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Real Serious Games 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 | -------------------------------------------------------------------------------- /Src/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Unity-Dependency-Injection")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Unity-Dependency-Injection")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("e872aa21-9bd1-4b59-9459-2632327d3d4f")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /Src/Unity-Dependency-Injection.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {E872AA21-9BD1-4B59-9459-2632327D3D4F} 8 | Library 9 | Properties 10 | Unity_Dependency_Injection 11 | Unity-Dependency-Injection 12 | v3.5 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | dlls\UnityEngine.dll 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 59 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | [Xx]64/ 19 | [Xx]86/ 20 | [Bb]uild/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | 85 | # Visual Studio profiler 86 | *.psess 87 | *.vsp 88 | *.vspx 89 | *.sap 90 | 91 | # TFS 2012 Local Workspace 92 | $tf/ 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | *.DotSettings.user 101 | 102 | # JustCode is a .NET coding add-in 103 | .JustCode 104 | 105 | # TeamCity is a build add-in 106 | _TeamCity* 107 | 108 | # DotCover is a Code Coverage Tool 109 | *.dotCover 110 | 111 | # NCrunch 112 | _NCrunch_* 113 | .*crunch*.local.xml 114 | nCrunchTemp_* 115 | 116 | # MightyMoose 117 | *.mm.* 118 | AutoTest.Net/ 119 | 120 | # Web workbench (sass) 121 | .sass-cache/ 122 | 123 | # Installshield output folder 124 | [Ee]xpress/ 125 | 126 | # DocProject is a documentation generator add-in 127 | DocProject/buildhelp/ 128 | DocProject/Help/*.HxT 129 | DocProject/Help/*.HxC 130 | DocProject/Help/*.hhc 131 | DocProject/Help/*.hhk 132 | DocProject/Help/*.hhp 133 | DocProject/Help/Html2 134 | DocProject/Help/html 135 | 136 | # Click-Once directory 137 | publish/ 138 | 139 | # Publish Web Output 140 | *.[Pp]ublish.xml 141 | *.azurePubxml 142 | 143 | # TODO: Un-comment the next line if you do not want to checkin 144 | # your web deploy settings because they may include unencrypted 145 | # passwords 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # NuGet Packages 150 | *.nupkg 151 | # The packages folder can be ignored because of Package Restore 152 | **/packages/* 153 | # except build/, which is used as an MSBuild target. 154 | !**/packages/build/ 155 | # Uncomment if necessary however generally it will be regenerated when needed 156 | #!**/packages/repositories.config 157 | # NuGet v3's project.json files produces more ignoreable files 158 | *.nuget.props 159 | *.nuget.targets 160 | 161 | # Microsoft Azure Build Output 162 | csx/ 163 | *.build.csdef 164 | 165 | # Microsoft Azure Emulator 166 | ecf/ 167 | rcf/ 168 | 169 | # Microsoft Azure ApplicationInsights config file 170 | ApplicationInsights.config 171 | 172 | # Windows Store app package directory 173 | AppPackages/ 174 | BundleArtifacts/ 175 | 176 | # Visual Studio cache files 177 | # files ending in .cache can be ignored 178 | *.[Cc]ache 179 | # but keep track of directories ending in .cache 180 | !*.[Cc]ache/ 181 | 182 | # Others 183 | ClientBin/ 184 | [Ss]tyle[Cc]op.* 185 | ~$* 186 | *~ 187 | *.dbmdl 188 | *.dbproj.schemaview 189 | *.pfx 190 | *.publishsettings 191 | node_modules/ 192 | orleans.codegen.cs 193 | 194 | # RIA/Silverlight projects 195 | Generated_Code/ 196 | 197 | # Backup & report files from converting an old project file 198 | # to a newer Visual Studio version. Backup files are not needed, 199 | # because we have git ;-) 200 | _UpgradeReport_Files/ 201 | Backup*/ 202 | UpgradeLog*.XML 203 | UpgradeLog*.htm 204 | 205 | # SQL Server files 206 | *.mdf 207 | *.ldf 208 | 209 | # Business Intelligence projects 210 | *.rdl.data 211 | *.bim.layout 212 | *.bim_*.settings 213 | 214 | # Microsoft Fakes 215 | FakesAssemblies/ 216 | 217 | # GhostDoc plugin setting file 218 | *.GhostDoc.xml 219 | 220 | # Node.js Tools for Visual Studio 221 | .ntvs_analysis.dat 222 | 223 | # Visual Studio 6 build log 224 | *.plg 225 | 226 | # Visual Studio 6 workspace options file 227 | *.opt 228 | 229 | # Visual Studio LightSwitch build output 230 | **/*.HTMLClient/GeneratedArtifacts 231 | **/*.DesktopClient/GeneratedArtifacts 232 | **/*.DesktopClient/ModelManifest.xml 233 | **/*.Server/GeneratedArtifacts 234 | **/*.Server/ModelManifest.xml 235 | _Pvt_Extensions 236 | 237 | # LightSwitch generated files 238 | GeneratedArtifacts/ 239 | ModelManifest.xml 240 | 241 | # Paket dependency manager 242 | .paket/paket.exe 243 | 244 | # FAKE - F# Make 245 | .fake/ -------------------------------------------------------------------------------- /Src/DependencyResolver.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Text; 6 | using UnityEngine; 7 | 8 | /// 9 | /// Helper class that resolves dependencies in the Unity scene. 10 | /// 11 | public class DependencyResolver 12 | { 13 | /// 14 | /// Enumerate the scene and find objects of interest to the dependency resolver. 15 | /// 16 | /// WARNING: This function can be expensive. Call it only once and cache the result if you need it. 17 | /// 18 | public void FindObjects(IEnumerable allGameObjects, List injectables) 19 | { 20 | foreach (var gameObject in allGameObjects) 21 | { 22 | foreach (var component in gameObject.GetComponents()) 23 | { 24 | var componentType = component.GetType(); 25 | var hasInjectableProperties = componentType.GetProperties() 26 | .Where(IsMemberInjectable) 27 | .Any(); 28 | if (hasInjectableProperties) 29 | { 30 | injectables.Add(component); 31 | } 32 | else 33 | { 34 | var hasInjectableFields = componentType.GetFields() 35 | .Where(IsMemberInjectable) 36 | .Any(); 37 | if (hasInjectableFields) 38 | { 39 | injectables.Add(component); 40 | } 41 | } 42 | 43 | if (componentType.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance) 44 | .Where(IsMemberInjectable) 45 | .Any()) 46 | { 47 | Debug.LogError("Private properties should not be marked with [Inject] atttribute!", component); 48 | } 49 | 50 | if (componentType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance) 51 | .Where(IsMemberInjectable) 52 | .Any()) 53 | { 54 | Debug.LogError("Private fields should not be marked with [Inject] atttribute!", component); 55 | } 56 | } 57 | } 58 | } 59 | 60 | /// 61 | /// Determine if a member requires dependency resolution, checks if it has the 'Inject' attribute. 62 | /// 63 | private bool IsMemberInjectable(MemberInfo member) 64 | { 65 | return member.GetCustomAttributes(true) 66 | .Where(attribute => attribute is InjectAttribute) 67 | .Count() > 0; 68 | } 69 | 70 | /// 71 | /// Use C# reflection to find all members of an object that require dependency resolution and injection. 72 | /// 73 | private IEnumerable FindInjectableMembers(MonoBehaviour injectable) 74 | { 75 | var type = injectable.GetType(); 76 | var injectableProperties = type.GetProperties() 77 | .Where(IsMemberInjectable) 78 | .Select(property => new InjectableProperty(property)) 79 | .Cast(); 80 | 81 | var injectableFields = type.GetFields() 82 | .Where(IsMemberInjectable) 83 | .Select(field => new InjectableField(field)) 84 | .Cast(); 85 | 86 | return injectableProperties.Concat(injectableFields); 87 | } 88 | 89 | /// 90 | /// Get the ancestors from a particular Game Object. This means the parent object, the grand parent and so on up to the root of the hierarchy. 91 | /// 92 | private IEnumerable GetAncestors(GameObject fromGameObject) 93 | { 94 | for (var parent = fromGameObject.transform.parent; parent != null; parent = parent.parent) 95 | { 96 | yield return parent.gameObject; // Mmmmm... LINQ. 97 | } 98 | } 99 | 100 | /// 101 | /// Find matching dependencies at a particular level in the hiearchy. 102 | /// 103 | private IEnumerable FindMatchingDependendencies(Type injectionType, GameObject gameObject) 104 | { 105 | foreach (var component in gameObject.GetComponents()) 106 | { 107 | if (injectionType.IsAssignableFrom(component.GetType())) 108 | { 109 | yield return component; 110 | } 111 | } 112 | } 113 | 114 | /// 115 | /// Find a single matching dependency at a particular level in the hierarchy. 116 | /// Returns null if none or multiple were found. 117 | /// 118 | private MonoBehaviour FindMatchingDependency(Type injectionType, GameObject gameObject, MonoBehaviour injectable) 119 | { 120 | var matchingDependencies = FindMatchingDependendencies(injectionType, gameObject).ToArray(); 121 | if (matchingDependencies.Length == 1) 122 | { 123 | // A single matching dep was found. 124 | return matchingDependencies[0]; 125 | } 126 | 127 | if (matchingDependencies.Length == 0) 128 | { 129 | // No deps were found. 130 | return null; 131 | } 132 | 133 | Debug.LogError( 134 | "Found multiple hierarchy dependencies that match injection type " + injectionType.Name + " to be injected into '" + injectable.name + "'. See following warnings.", 135 | injectable 136 | ); 137 | 138 | foreach (var dependency in matchingDependencies) 139 | { 140 | Debug.LogWarning(" Duplicate dependencies: '" + dependency.name + "'.", dependency); 141 | } 142 | 143 | return null; 144 | } 145 | 146 | /// 147 | /// Walk up the hierarchy (towards the root) and find an injectable dependency that matches the specified type. 148 | /// 149 | private MonoBehaviour FindDependencyInHierarchy(Type injectionType, MonoBehaviour injectable) 150 | { 151 | foreach (var ancestor in GetAncestors(injectable.gameObject)) 152 | { 153 | var dependency = FindMatchingDependency(injectionType, ancestor, injectable); 154 | if (dependency != null) 155 | { 156 | return dependency; 157 | } 158 | } 159 | 160 | return null; 161 | } 162 | 163 | /// 164 | /// Represents a member (property or field) of an object that have a dependency injected. 165 | /// 166 | public interface IInjectableMember 167 | { 168 | /// 169 | /// The one thing we want to do is set the value of the member. 170 | /// 171 | void SetValue(object owner, object value); 172 | 173 | /// 174 | /// Get the name of the member. 175 | /// 176 | string Name { get; } 177 | 178 | /// 179 | /// Get the type of the member. 180 | /// 181 | Type MemberType { get; } 182 | 183 | /// 184 | /// The category of the member (field or property). 185 | /// 186 | string Category { get; } 187 | 188 | /// 189 | /// Specifies where the dependency is allowed to be injected from. 190 | /// 191 | InjectFrom InjectFrom { get; } 192 | } 193 | 194 | /// 195 | /// Represents a property of an object that have a dependency injected. 196 | /// 197 | public class InjectableProperty : IInjectableMember 198 | { 199 | private PropertyInfo propertyInfo; 200 | 201 | public InjectableProperty(PropertyInfo propertyInfo) 202 | { 203 | this.propertyInfo = propertyInfo; 204 | var injectAttribute = propertyInfo.GetCustomAttributes(typeof(InjectAttribute), false) 205 | .Cast() 206 | .Single(); 207 | this.InjectFrom = injectAttribute.InjectFrom; 208 | } 209 | 210 | /// 211 | /// The one thing we want to do is set the value of the member. 212 | /// 213 | public void SetValue(object owner, object value) 214 | { 215 | propertyInfo.SetValue(owner, value, null); 216 | } 217 | 218 | /// 219 | /// Get the name of the member. 220 | /// 221 | public string Name 222 | { 223 | get 224 | { 225 | return propertyInfo.Name; 226 | } 227 | } 228 | 229 | /// 230 | /// Get the type of the member. 231 | /// 232 | public Type MemberType 233 | { 234 | get 235 | { 236 | return propertyInfo.PropertyType; 237 | } 238 | } 239 | 240 | /// 241 | /// The category of the member (field or property). 242 | /// 243 | public string Category 244 | { 245 | get 246 | { 247 | return "property"; 248 | } 249 | } 250 | 251 | /// 252 | /// Specifies where the dependency is allowed to be injected from. 253 | /// 254 | public InjectFrom InjectFrom 255 | { 256 | get; 257 | private set; 258 | } 259 | } 260 | 261 | /// 262 | /// Represents a field of an object that have a dependency injected. 263 | /// 264 | public class InjectableField : IInjectableMember 265 | { 266 | private FieldInfo fieldInfo; 267 | 268 | public InjectableField(FieldInfo fieldInfo) 269 | { 270 | this.fieldInfo = fieldInfo; 271 | var injectAttribute = fieldInfo.GetCustomAttributes(typeof(InjectAttribute), false) 272 | .Cast() 273 | .Single(); 274 | this.InjectFrom = injectAttribute.InjectFrom; 275 | } 276 | 277 | /// 278 | /// The one thing we want to do is set the value of the member. 279 | /// 280 | public void SetValue(object owner, object value) 281 | { 282 | fieldInfo.SetValue(owner, value); 283 | } 284 | 285 | /// 286 | /// Get the name of the member. 287 | /// 288 | public string Name 289 | { 290 | get 291 | { 292 | return fieldInfo.Name; 293 | } 294 | } 295 | 296 | /// 297 | /// Get the type of the member. 298 | /// 299 | public Type MemberType 300 | { 301 | get 302 | { 303 | return fieldInfo.FieldType; 304 | } 305 | } 306 | 307 | /// 308 | /// The category of the member (field or property). 309 | /// 310 | public string Category 311 | { 312 | get 313 | { 314 | return "field"; 315 | } 316 | } 317 | 318 | /// 319 | /// Specifies where the dependency is allowed to be injected from. 320 | /// 321 | public InjectFrom InjectFrom 322 | { 323 | get; 324 | private set; 325 | } 326 | } 327 | 328 | /// 329 | /// Attempt to resolve a member dependency by scanning up the hiearchy for a MonoBehaviour that mathces the injection type. 330 | /// 331 | private bool ResolveMemberDependencyFromHierarchy(MonoBehaviour injectable, IInjectableMember injectableMember) 332 | { 333 | // Find a match in the hierarchy. 334 | var toInject = FindDependencyInHierarchy(injectableMember.MemberType, injectable); 335 | if (toInject != null) 336 | { 337 | try 338 | { 339 | Debug.Log("Injecting " + toInject.GetType().Name + " from hierarchy (GameObject: '" + toInject.gameObject.name + "') into " + injectable.GetType().Name + " at " + injectableMember.Category + " " + injectableMember.Name + " on GameObject '" + injectable.name + "'.", injectable); 340 | 341 | injectableMember.SetValue(injectable, toInject); 342 | } 343 | catch (Exception ex) 344 | { 345 | Debug.LogException(ex, injectable); // Bad type??! 346 | } 347 | 348 | return true; 349 | } 350 | else 351 | { 352 | // Failed to find a match. 353 | return false; 354 | } 355 | } 356 | 357 | /// 358 | /// Attempt to resolve a member dependency from anywhere in the scene. 359 | /// Returns false is no such dependency was found. 360 | /// 361 | private bool ResolveMemberDependencyFromAnywhere(MonoBehaviour injectable, IInjectableMember injectableMember) 362 | { 363 | if (injectableMember.MemberType.IsArray) 364 | { 365 | return ResolveArrayDependencyFromAnywhere(injectable, injectableMember); 366 | } 367 | else 368 | { 369 | return ResolveObjectDependencyFromAnywhere(injectable, injectableMember); 370 | } 371 | } 372 | 373 | /// 374 | /// Resolve an array dependency from objects anywhere in the scene. 375 | /// 376 | private static bool ResolveArrayDependencyFromAnywhere(MonoBehaviour injectable, IInjectableMember injectableMember) 377 | { 378 | var elementType = injectableMember.MemberType.GetElementType(); 379 | var toInject = GameObject.FindObjectsOfType(elementType); 380 | if (toInject != null) 381 | { 382 | try 383 | { 384 | Debug.Log("Injecting array of " + toInject.Length + " elements into " + injectable.GetType().Name + " at " + injectableMember.Category + " " + injectableMember.Name + " on GameObject '" + injectable.name + "'.", injectable); 385 | 386 | foreach (var component in toInject.Cast()) 387 | { 388 | Debug.Log("> Injecting object " + component.GetType().Name + " (GameObject: '" + component.gameObject.name + "').", injectable); 389 | } 390 | 391 | // 392 | // Create an appropriately typed array so that we don't get a type error when setting the value. 393 | // 394 | var typedArray = Array.CreateInstance(elementType, toInject.Length); 395 | Array.Copy(toInject, typedArray, toInject.Length); 396 | 397 | injectableMember.SetValue(injectable, typedArray); 398 | } 399 | catch (Exception ex) 400 | { 401 | Debug.LogException(ex, injectable); 402 | } 403 | 404 | return true; 405 | } 406 | else 407 | { 408 | return false; 409 | } 410 | } 411 | 412 | /// 413 | /// Resolve an object dependency from objects anywhere in the scene. 414 | /// 415 | private static bool ResolveObjectDependencyFromAnywhere(MonoBehaviour injectable, IInjectableMember injectableMember) 416 | { 417 | var toInject = (MonoBehaviour)GameObject.FindObjectOfType(injectableMember.MemberType); 418 | if (toInject != null) 419 | { 420 | try 421 | { 422 | Debug.Log("Injecting object " + toInject.GetType().Name + " (GameObject: '" + toInject.gameObject.name + "') into " + injectable.GetType().Name + " at " + injectableMember.Category + " " + injectableMember.Name + " on GameObject '" + injectable.name + "'.", injectable); 423 | 424 | injectableMember.SetValue(injectable, toInject); 425 | } 426 | catch (Exception ex) 427 | { 428 | Debug.LogException(ex, injectable); 429 | } 430 | 431 | return true; 432 | } 433 | else 434 | { 435 | return false; 436 | } 437 | } 438 | 439 | /// 440 | /// Resolve a member dependency and inject the resolved valued. 441 | /// 442 | private void ResolveMemberDependency(MonoBehaviour injectable, IInjectableMember injectableMember) 443 | { 444 | if (injectableMember.InjectFrom == InjectFrom.Above) 445 | { 446 | if (!ResolveMemberDependencyFromHierarchy(injectable, injectableMember)) 447 | { 448 | Debug.LogError( 449 | "Failed to resolve dependency for " + injectableMember.Category + ". Member: " + injectableMember.Name + ", MonoBehaviour: " + injectable.GetType().Name + ", GameObject: " + injectable.gameObject.name + "\r\n" + 450 | "Failed to find a dependency that matches " + injectableMember.MemberType.Name + ".", 451 | injectable 452 | ); 453 | } 454 | } 455 | else if (injectableMember.InjectFrom == InjectFrom.Anywhere) 456 | { 457 | if (!ResolveMemberDependencyFromAnywhere(injectable, injectableMember)) 458 | { 459 | Debug.LogError( 460 | "Failed to resolve dependency for " + injectableMember.Category + ". Member: " + injectableMember.Name + ", MonoBehaviour: " + injectable.GetType().Name + ", GameObject: " + injectable.gameObject.name + "\r\n" + 461 | "Failed to find a dependency that matches " + injectableMember.MemberType.Name + ".", 462 | injectable 463 | ); 464 | } 465 | } 466 | else 467 | { 468 | throw new ApplicationException("Unexpected use of InjectFrom enum: " + injectableMember.InjectFrom); 469 | } 470 | } 471 | 472 | /// 473 | /// Resolve dependenies for an 'injectable' object. 474 | /// 475 | private void ResolveDependencies(MonoBehaviour injectable) 476 | { 477 | var injectableProperties = FindInjectableMembers(injectable); 478 | foreach (var injectableMember in injectableProperties) 479 | { 480 | ResolveMemberDependency(injectable, injectableMember); 481 | } 482 | } 483 | 484 | /// 485 | /// Resolve all depenencies in the entire scene. 486 | /// 487 | public void ResolveScene() 488 | { 489 | var allGameObjects = GameObject.FindObjectsOfType(); 490 | Resolve(allGameObjects); 491 | } 492 | 493 | /// 494 | /// Resolve a subset of the hierarchy downwards from a particular object. 495 | /// 496 | public void Resolve(GameObject parent) 497 | { 498 | var gameObjects = new GameObject[] { parent }; 499 | Resolve(gameObjects); 500 | } 501 | 502 | /// 503 | /// Resolve dependencies for the hierarchy downwards from a set of game objects. 504 | /// 505 | public void Resolve(IEnumerable gameObjects) 506 | { 507 | var injectables = new List(); 508 | FindObjects(gameObjects, injectables); // Scan the scene for objects of interest! 509 | 510 | foreach (var injectable in injectables) 511 | { 512 | ResolveDependencies(injectable); 513 | } 514 | } 515 | } 516 | --------------------------------------------------------------------------------