FindReferencedModule <T>() where T : Module, new() { if (null == this.BuildEnvironmentInternal) { throw new Exception("Unable to find a module within a patch - please change the calling code to invoke this outside of the patch, but in the module's Init method"); } var referencedModules = this.ReferencedModules[this.BuildEnvironmentInternal]; var matches = referencedModules.Where(item => item.GetType() == typeof(T)); var matchedModule = matches.FirstOrDefault(); if (null != matchedModule) { return(matchedModule as T); } this.CommonModuleType.Push(typeof(T)); var newModule = Module.Create <T>(preInitCallback: module => { if (null != module) { referencedModules.Add(module); } }); this.CommonModuleType.Pop(); return(newModule); }
FindReferencedModule <T>() where T : Module, new() { if (null == this.BuildEnvironmentInternal) { var message = new System.Text.StringBuilder(); message.AppendLine("Unable to find a module either within a patch or after the build has started."); message.AppendLine("If called within a patch function, please modify the calling code to invoke this call within the module's Init method."); message.AppendLine("If it must called elsewhere, please use the overloaded version accepting an Environment argument."); throw new Exception(message.ToString()); } var referencedModules = this.ReferencedModules[this.BuildEnvironmentInternal]; var matchedModule = referencedModules.FirstOrDefault(item => item.GetType() == typeof(T)); if (null != matchedModule) { return(matchedModule as T); } this.CommonModuleType.Push(typeof(T)); try { var newModule = Module.Create <T>(preInitCallback: module => { if (null != module) { referencedModules.Add(module); } }); return(newModule); } catch (UnableToBuildModuleException) { // remove the failed to create module from the referenced list // and also any modules and strings created in its Init function, potentially // of child module types var moduleTypeToRemove = this.CommonModuleType.Peek(); TokenizedString.RemoveEncapsulatedStrings(moduleTypeToRemove); Module.RemoveEncapsulatedModules(moduleTypeToRemove); referencedModules.Remove(referencedModules.First(item => item.GetType() == typeof(T))); var moduleEnvList = this.Modules[this.BuildEnvironmentInternal]; moduleEnvList.Remove(moduleEnvList.First(item => item.GetType() == typeof(T))); throw; } finally { this.CommonModuleType.Pop(); } }