private static object FetchNewInstanceOfAnnotationComplexType()

in src/Readers/Vipr.Reader.OData.v4/ODataVocabularyReader.cs [392:436]


        private static object FetchNewInstanceOfAnnotationComplexType(IEdmType type)
        {
            var complexType = type as IEdmComplexType;
            if (complexType == null)
                throw new ArgumentNullException("type",
                    "Type must be non-null and of type IEdmComplexType to obtain new instance");

            // We should attempt to cache these constructors so this code does not get called repeatedly 
            Func<object> constructor;
            if (_constructorCache == null)
            {
                _constructorCache = new Dictionary<IEdmType, Func<object>>();
            }

            if (!_constructorCache.TryGetValue(type, out constructor))
            {
                var viprCodeModelNamespace = VocabularyNamespaceMappings[complexType.Namespace];

                // We should cache a reference to the assembly rather than obtaining it every time.
                if (_viprCore == null)
                {
                    var viprCoreName =
                        Assembly.GetExecutingAssembly().GetReferencedAssemblies().First(a => a.Name == "Vipr.Core");
                    _viprCore = Assembly.Load(viprCoreName);
                }

                try
                {
                    // Fetch the appropriate vocabulary instance type from the Vipr.Core CodeModel
                    var t = _viprCore.GetType(string.Format("{0}.{1}", viprCodeModelNamespace, complexType.Name),
                        throwOnError: true);

                    // Cache an action to call to create this type.
                    constructor = () => CreateDefaultInstance(t);
                    _constructorCache[type] = constructor;
                }
                catch
                {
                    return null;
                }
            }

            // Call the cached constructor and return the instance
            return constructor();
        }