예제 #1
0
 public static IEnumerable <TypeInfo> Cast(this TypeInfos src)
 {
     foreach (TypeInfo item in src)
     {
         yield return(item);
     }
 }
예제 #2
0
파일: TypeTree.cs 프로젝트: jacko12549/EvoS
        public TypeTree(StreamReader stream)
        {
            Attributes = stream.ReadInt32();
            Embeded    = stream.ReadByte();

            var baseClassCount = stream.ReadInt32();

            for (var i = 0; i < baseClassCount; i++)
            {
                var entry = new TypeEntry(stream)
                {
                    Index = i
                };
                BaseClasses.Add(entry);

                if (Embeded == 0)
                {
                    continue;
                }

                if (entry.TypeId == (int)CommonTypeIds.MonoBehaviour)
                {
                    var info = new TypeTreeInfo(stream);
                    if (!ScriptTypeInfos.TryAdd(entry.Unknown2, info))
                    {
                        Log.Print(LogType.Warning, $"Multiple scripts with id={entry.Unknown2}!");
                    }
                }
                else
                {
                    TypeInfos.Add(entry.TypeId, new TypeTreeInfo(stream));
                }
            }
        }
예제 #3
0
        private static void CollectEnumInfos(
            IEnumerable <EnumTypeExtensionNode> enumTypeExtensions,
            Dictionary <NameString, LeafTypeInfo> leafTypes,
            TypeInfos typeInfos)
        {
            foreach (EnumTypeExtensionNode scalarTypeExtension in enumTypeExtensions)
            {
                if (!leafTypes.TryGetValue(
                        scalarTypeExtension.Name.Value,
                        out LeafTypeInfo scalarInfo))
                {
                    var runtimeType       = GetRuntimeType(scalarTypeExtension);
                    var serializationType = GetSerializationType(scalarTypeExtension);

                    TryRegister(typeInfos, runtimeType);
                    TryRegister(typeInfos, serializationType);

                    scalarInfo = new LeafTypeInfo(
                        scalarTypeExtension.Name.Value,
                        runtimeType?.Name,
                        serializationType?.Name);
                    leafTypes.Add(scalarInfo.TypeName, scalarInfo);
                }
            }
        }
        public static void Map(ClientModel model, IMapperContext context)
        {
            foreach (OperationModel modelOperation in model.Operations)
            {
                RuntimeTypeInfo resultType = context.GetRuntimeType(
                    modelOperation.ResultType.Name,
                    Descriptors.TypeDescriptors.TypeKind.ResultType);

                context.Register(
                    modelOperation.Name,
                    new ResultBuilderDescriptor(
                        new RuntimeTypeInfo(
                            CreateResultBuilderName(modelOperation.Name),
                            CreateStateNamespace(context.Namespace)),
                        context.Types.Single(t => t.RuntimeType.Equals(resultType)),
                        modelOperation.LeafTypes.Select(
                            leafType =>
                {
                    string runtimeType =
                        leafType.RuntimeType.Contains('.')
                                        ? leafType.RuntimeType
                                        : $"{context.Namespace}.{leafType.RuntimeType}";

                    string serializationType =
                        leafType.SerializationType.Contains('.')
                                        ? leafType.SerializationType
                                        : $"{context.Namespace}.{leafType.SerializationType}";

                    return(new ValueParserDescriptor(
                               leafType.Name,
                               TypeInfos.GetOrCreate(runtimeType),
                               TypeInfos.GetOrCreate(serializationType)));
                }).ToList()));
            }
        }
예제 #5
0
        public static void Map(ClientModel model, IMapperContext context)
        {
            var entities = new List <EntityIdDescriptor>();

            foreach (var entity in model.Entities)
            {
                var fields = new List <ScalarEntityIdDescriptor>();

                foreach (var field in entity.Fields)
                {
                    if (field.Type.NamedType() is ILeafType leafType)
                    {
                        fields.Add(
                            new ScalarEntityIdDescriptor(
                                field.Name,
                                leafType.Name,
                                TypeInfos.From(leafType.GetSerializationType())));
                    }
                }

                entities.Add(
                    new EntityIdDescriptor(entity.Name, entity.Name, fields));
            }

            context.Register(
                new EntityIdFactoryDescriptor(
                    context.ClientName + "EntityIdFactory",
                    entities,
                    NamingConventions.CreateStateNamespace(context.Namespace)));
        }
예제 #6
0
        public List <HeaderType> Parse(Row[] rows)
        {
            ///  Single Header Format
            ///  ex : id:int[:key]
            ///  ex : damageFactor:float
            ///  ex : name:string

            if (rows.Length != 1)
            {
                throw new Exception("Rows Length Invalid");
            }

            Row row = rows[0];

            List <HeaderType> headerTypeList = new List <HeaderType>();

            foreach (var cell in row.FilledCells)
            {
                if (cell.ReferenceIndex < Configuration.StartCol)
                {
                    continue;
                }

                if (cell.Text.Length == 0 || Configuration.PrefixIgnoreColumn.Any(x => x == cell.Text[0]))
                {
                    continue;
                }

                string[] typeStr = cell.Text.Split(':');

                var isKey = false;
                if (typeStr.Length == 3 &&
                    string.Equals(typeStr[2], "key", StringComparison.OrdinalIgnoreCase))
                {
                    isKey = true;
                }

                HeaderType headerType = new HeaderType()
                {
                    Reference      = cell.Reference,
                    ReferenceIndex = cell.ReferenceIndex,
                    ValueName      = typeStr[0],
                    ValueType      = typeStr[1],
                    ValueRealType  = TypeInfos.ConvertRealType(typeStr[1]),
                    IsKey          = isKey
                };

                headerTypeList.Add(headerType);
            }

            return(headerTypeList);
        }
예제 #7
0
        public List <HeaderType> Parse(Row[] rows)
        {
            if (rows.Length != 2)
            {
                throw new Exception("Rows Length Invalid");
            }

            List <HeaderType> headerTypeList = new List <HeaderType>();

            Row row     = rows[0];
            Row rowType = rows[1];

            for (int i = 0; i < row.FilledCells.Length; i++)
            {
                Cell cell     = row.FilledCells[i];
                int  refIndex = Cell.GetCellReferenceIndex(cell.Reference);
                Cell cellType = rowType.FilledCells[refIndex];

                if (cell.ReferenceIndex < Configuration.StartCol)
                {
                    continue;
                }

                if (cell.Text.Length == 0 || (Configuration.PrefixIgnoreColumn.Any(x => x == cell.Text[0]) ||
                                              Configuration.PrefixIgnoreColumn.Any(x => x == cellType.Text[0])))
                {
                    continue;
                }

                string[] typeStr = cellType.Text.Split(':');

                var isKey = false;
                if (typeStr.Length == 2 &&
                    string.Equals(typeStr[1], "key", StringComparison.OrdinalIgnoreCase))
                {
                    isKey = true;
                }

                HeaderType headerType = new HeaderType()
                {
                    Reference     = cell.Reference,
                    ValueName     = cell.Text,
                    ValueType     = typeStr[0],
                    ValueRealType = TypeInfos.ConvertRealType(typeStr[0]),
                    IsKey         = isKey
                };

                headerTypeList.Add(headerType);
            }

            return(headerTypeList);
        }
예제 #8
0
 public EnumTypeDescriptor(
     NameString name,
     RuntimeTypeInfo runtimeType,
     RuntimeTypeInfo?underlyingType,
     IReadOnlyList <EnumValueDescriptor> values,
     string?documentation)
 {
     Name              = name;
     RuntimeType       = runtimeType;
     SerializationType = TypeInfos.From(TypeNames.String);
     UnderlyingType    = underlyingType;
     Values            = values;
 }
예제 #9
0
        private TypeInfo RegisterTypeInfo(string name)
        {
            _nodeSource += 1;
            var ti = new TypeInfo()
            {
                Name        = name,
                Description = "",
                TypeInfoId  = _nodeSource,
            };

            TypeInfos.Add(ti);
            return(ti);
        }
예제 #10
0
        public static string GetContentType(string path, byte[] content)
        {
            var retVal = DefaultContentType;

            var types = TypeInfos.Where(t => t.IsThisContentType(path, content));

            if (types.Any())
            {
                retVal = types.First().ContentType;
            }

            return(retVal);
        }
예제 #11
0
        /// <summary>
        /// Load all entity definitions
        /// </summary>
        private static void LoadEntities()
        {
            // Retrieve asset path and build entity database path
            var path = Path.Combine(Paths.DataDirectory, "json", "entities");

            // Inspect every JSON document and save in cache
            foreach (var file in Directory.GetFiles(path, "*.json", SearchOption.AllDirectories))
            {
                // File is a full path to the particular document
                try
                {
                    // Parse JSON file
                    using (var fileReader = File.OpenText(file))
                        using (var jsonReader = new JsonTextReader(fileReader))
                        {
                            // Since we want to allow multiple entity definitions in a single file, we require
                            // the top level structure to be an array.
                            var dataSource = JArray.ReadFrom(jsonReader) as JArray;

                            // Loop through all entity definitions. They have to be objects.
                            foreach (var entry in dataSource)
                            {
                                if (entry.Type != JTokenType.Object)
                                {
                                    continue;
                                }

                                // Found an object.
                                var currentObject = entry as JObject;

                                // Try to create entity type info object and store in cache
                                var info = new EntityTypeInfo(currentObject);
                                TypeInfos.Add(info.Name, info);

                                // Store JSON object in cache for later use
                                JsonObjectCache.Add(info.Name, currentObject);
                            }
                        }
                }
                catch (Exception e)
                {
                    Logger.PostMessageTagged(SeverityLevel.Fatal, "EntityManager",
                                             String.Format("Failed to load entity definition file \"{0}\": {1}", Path.GetFileName(file), e.Message));

                    throw;
                }
            }

            Logger.PostMessageTagged(SeverityLevel.Debug, "EntityManager",
                                     $"Loaded {TypeInfos.Count} entity types");
        }
예제 #12
0
        /// <summary>
        /// Registers a directory to the record.
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="parentId"></param>
        /// <param name="depth"></param>
        /// <returns></returns>
        /// <exception cref="ParentNotFoundException"></exception>
        public FileNode RegisterFile(string filePath, ulong parentId, ulong depth)
        {
            var fi = new FileInfo(filePath);

            var parentNode = PathNodes.FirstOrDefault(pns => pns.PathNodeId == parentId) ??
                             RegisterParent(fi.DirectoryName);

            // check if file type already exists, else create new file type
            var typeInfo = TypeInfos.FirstOrDefault(ti => ti.Name == fi.Extension) ??
                           RegisterTypeInfo(fi.Extension);

            // register the file
            var fileNode = new FileNode()
            {
                TypeInfoId = typeInfo.TypeInfoId,
                Name       = fi.Name,
                Bytes      = fi.Length,
                ParentId   = parentNode.PathNodeId,
                Depth      = depth,
            };

            FileNodes.Add(fileNode);

            // check if typeaggregate is already registered.
            var typeAggregate =
                TypeAggregates.FirstOrDefault(ta =>
                                              ta.TypeInfoId == typeInfo.TypeInfoId && ta.PathNodeId == parentNode.PathNodeId);

            if (typeAggregate == null)
            {
                typeAggregate = new TypeAggregate()
                {
                    TypeInfoId = typeInfo.TypeInfoId,
                    PathNodeId = parentNode.PathNodeId,
                    Count      = 1,
                    Bytes      = fi.Length
                };
                TypeAggregates.Add(typeAggregate);
            }
            else
            {
                typeAggregate.Count = typeAggregate.Count + 1;
                typeAggregate.Bytes = typeAggregate.Bytes + fi.Length;
            }

            Count = Count + 1;
            Bytes = Bytes + fi.Length;

            return(fileNode);
        }
예제 #13
0
        /// <summary>
        /// Генерирование ModBus-карты для Альфа-сервера
        /// </summary>
        public void Generate()
        {
            Bindings = new Bindings();
            DeviceType typeInfo;
            int        addr = 0;

            // конкатенация
            foreach (Device device in Devices)
            {
                if (device.IsIgnore)
                {
                    continue;
                }
                typeInfo = TypeInfos.Single(t => t.TypeName.Equals(device.Type));
                foreach (KeyValuePair <string, string> prop in typeInfo.Propertys)
                {
                    addr = AddNewBinding(Bindings, addr, device, prop);
                }
            }
        }
예제 #14
0
 /// <summary>
 /// Check if an entity type with given string identifier is known.
 /// </summary>
 /// <param name="type">String identifier to check for</param>
 /// <returns>Flag indicating presence of an entity type with given identifier</returns>
 public static bool HasEntityType(string type)
 {
     return(TypeInfos.ContainsKey(type));
 }
        private static ICode GenerateInternalMethodBody(
            CSharpSyntaxGeneratorSettings settings,
            DependencyInjectionDescriptor descriptor,
            TransportProfile profile)
        {
            var rootNamespace = descriptor.ClientDescriptor.RuntimeType.Namespace;

            var hasSubscriptions =
                descriptor.Operations.OfType <SubscriptionOperationDescriptor>().Any();
            var hasQueries =
                descriptor.Operations.OfType <QueryOperationDescriptor>().Any();
            var hasMutations =
                descriptor.Operations.OfType <MutationOperationDescriptor>().Any();

            CodeBlockBuilder body = CodeBlockBuilder
                                    .New()
                                    .AddCode(CreateBaseCode(settings));

            var generatedConnections = new HashSet <TransportType>();

            if (hasSubscriptions)
            {
                generatedConnections.Add(profile.Subscription);
                body.AddCode(
                    RegisterConnection(profile.Subscription, descriptor.Name));
            }

            if (hasQueries && !generatedConnections.Contains(profile.Query))
            {
                generatedConnections.Add(profile.Query);
                body.AddCode(RegisterConnection(profile.Query, descriptor.Name));
            }

            if (hasMutations && !generatedConnections.Contains(profile.Mutation))
            {
                generatedConnections.Add(profile.Mutation);
                body.AddCode(RegisterConnection(profile.Mutation, descriptor.Name));
            }

            body.AddEmptyLine();

            foreach (var typeDescriptor in descriptor.TypeDescriptors
                     .OfType <INamedTypeDescriptor>())
            {
                if (typeDescriptor.Kind == TypeKind.EntityType && !typeDescriptor.IsInterface())
                {
                    INamedTypeDescriptor namedTypeDescriptor =
                        (INamedTypeDescriptor)typeDescriptor.NamedType();
                    NameString className = namedTypeDescriptor.ExtractMapperName();

                    var interfaceName =
                        TypeNames.IEntityMapper.WithGeneric(
                            namedTypeDescriptor.ExtractType().ToString(),
                            $"{rootNamespace}.{typeDescriptor.RuntimeType.Name}");

                    body.AddMethodCall()
                    .SetMethodName(TypeNames.AddSingleton)
                    .AddGeneric(interfaceName)
                    .AddGeneric($"{CreateStateNamespace(rootNamespace)}.{className}")
                    .AddArgument(_services);
                }
            }

            body.AddEmptyLine();

            foreach (var enumType in descriptor.EnumTypeDescriptor)
            {
                body.AddMethodCall()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(TypeNames.ISerializer)
                .AddGeneric(CreateEnumParserName($"{rootNamespace}.{enumType.Name}"))
                .AddArgument(_services);
            }

            foreach (var serializer in _serializers)
            {
                body.AddMethodCall()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(TypeNames.ISerializer)
                .AddGeneric(serializer)
                .AddArgument(_services);
            }

            RuntimeTypeInfo stringTypeInfo = TypeInfos.From(TypeNames.String);

            foreach (var scalar in descriptor.TypeDescriptors.OfType <ScalarTypeDescriptor>())
            {
                if (scalar.RuntimeType.Equals(stringTypeInfo) &&
                    scalar.SerializationType.Equals(stringTypeInfo) &&
                    !BuiltInScalarNames.IsBuiltInScalar(scalar.Name))
                {
                    body.AddMethodCall()
                    .SetMethodName(TypeNames.AddSingleton)
                    .AddGeneric(TypeNames.ISerializer)
                    .AddArgument(_services)
                    .AddArgument(MethodCallBuilder
                                 .Inline()
                                 .SetNew()
                                 .SetMethodName(TypeNames.StringSerializer)
                                 .AddArgument(scalar.Name.AsStringToken()));
                }
            }

            foreach (var inputTypeDescriptor in descriptor.TypeDescriptors
                     .Where(x => x.Kind is TypeKind.InputType))
            {
                var formatter =
                    CreateInputValueFormatter(
                        (InputObjectTypeDescriptor)inputTypeDescriptor.NamedType());

                body.AddMethodCall()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(TypeNames.ISerializer)
                .AddGeneric($"{rootNamespace}.{formatter}")
                .AddArgument(_services);
            }

            body.AddCode(RegisterSerializerResolver());

            body.AddEmptyLine();

            foreach (var operation in descriptor.Operations)
            {
                if (!(operation.ResultTypeReference is InterfaceTypeDescriptor typeDescriptor))
                {
                    continue;
                }

                TransportType operationKind = operation switch
                {
                    SubscriptionOperationDescriptor => profile.Subscription,
                    QueryOperationDescriptor => profile.Query,
                    MutationOperationDescriptor => profile.Mutation,
                    _ => throw ThrowHelper.DependencyInjection_InvalidOperationKind(operation)
                };

                string connectionKind = operationKind switch
                {
                    TransportType.Http => TypeNames.IHttpConnection,
                    TransportType.WebSocket => TypeNames.IWebSocketConnection,
                    TransportType.InMemory => TypeNames.IInMemoryConnection,
                    { } v => throw ThrowHelper.DependencyInjection_InvalidTransportType(v)
                };

                string operationName          = operation.Name;
                string fullName               = operation.RuntimeType.ToString();
                string operationInterfaceName = operation.InterfaceType.ToString();
                string resultInterface        = typeDescriptor.RuntimeType.ToString();

                // The factories are generated based on the concrete result type, which is the
                // only implementee of the result type interface.

                var factoryName =
                    CreateResultFactoryName(
                        typeDescriptor.ImplementedBy.First().RuntimeType.Name);

                var builderName = CreateResultBuilderName(operationName);
                body.AddCode(
                    RegisterOperation(
                        settings,
                        connectionKind,
                        fullName,
                        operationInterfaceName,
                        resultInterface,
                        $"{CreateStateNamespace(operation.RuntimeType.Namespace)}.{factoryName}",
                        $"{CreateStateNamespace(operation.RuntimeType.Namespace)}.{builderName}"));
            }

            if (settings.IsStoreEnabled())
            {
                body.AddCode(
                    MethodCallBuilder
                    .New()
                    .SetMethodName(TypeNames.AddSingleton)
                    .AddGeneric(TypeNames.IEntityIdSerializer)
                    .AddGeneric(descriptor.EntityIdFactoryDescriptor.Type.ToString())
                    .AddArgument(_services));
            }

            body.AddCode(
                MethodCallBuilder
                .New()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(descriptor.ClientDescriptor.RuntimeType.ToString())
                .AddArgument(_services));

            body.AddCode(
                MethodCallBuilder
                .New()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(descriptor.ClientDescriptor.InterfaceType.ToString())
                .AddArgument(_services)
                .AddArgument(LambdaBuilder
                             .New()
                             .AddArgument(_sp)
                             .SetCode(MethodCallBuilder
                                      .Inline()
                                      .SetMethodName(TypeNames.GetRequiredService)
                                      .AddGeneric(descriptor.ClientDescriptor.RuntimeType.ToString())
                                      .AddArgument(_sp))));

            body.AddLine($"return {_services};");

            return(body);
        }
예제 #16
0
        public static ISchema Load(
            IReadOnlyCollection <GraphQLFile> schemaFiles,
            bool strictValidation = true,
            bool noStore          = false)
        {
            if (schemaFiles is null)
            {
                throw new ArgumentNullException(nameof(schemaFiles));
            }

            var typeInfos = new TypeInfos();
            var lookup    = new Dictionary <ISyntaxNode, string>();

            IndexSyntaxNodes(schemaFiles, lookup);

            var builder = SchemaBuilder.New();

            builder.ModifyOptions(o => o.StrictValidation = strictValidation);

            var leafTypes            = new Dictionary <NameString, LeafTypeInfo>();
            var globalEntityPatterns = new List <SelectionSetNode>();
            var typeEntityPatterns   = new Dictionary <NameString, SelectionSetNode>();

            foreach (DocumentNode document in schemaFiles.Select(f => f.Document))
            {
                if (document.Definitions.Any(t => t is ITypeSystemExtensionNode))
                {
                    CollectScalarInfos(
                        document.Definitions.OfType <ScalarTypeExtensionNode>(),
                        leafTypes,
                        typeInfos);

                    CollectEnumInfos(
                        document.Definitions.OfType <EnumTypeExtensionNode>(),
                        leafTypes,
                        typeInfos);

                    if (!noStore)
                    {
                        CollectGlobalEntityPatterns(
                            document.Definitions.OfType <SchemaExtensionNode>(),
                            globalEntityPatterns);

                        CollectTypeEntityPatterns(
                            document.Definitions.OfType <ObjectTypeExtensionNode>(),
                            typeEntityPatterns);
                    }
                }
                else
                {
                    foreach (var scalar in document.Definitions.OfType <ScalarTypeDefinitionNode>())
                    {
                        if (!BuiltInScalarNames.IsBuiltInScalar(scalar.Name.Value))
                        {
                            builder.AddType(new AnyType(
                                                scalar.Name.Value,
                                                scalar.Description?.Value));
                        }
                    }

                    builder.AddDocument(document);
                }
            }

            AddDefaultScalarInfos(leafTypes);

            return(builder
                   .SetSchema(d => d.Extend().OnBeforeCreate(
                                  c => c.ContextData.Add(_typeInfosKey, typeInfos)))
                   .TryAddTypeInterceptor(
                       new LeafTypeInterceptor(leafTypes))
                   .TryAddTypeInterceptor(
                       new EntityTypeInterceptor(globalEntityPatterns, typeEntityPatterns))
                   .Use(_ => _ => throw new NotSupportedException())
                   .Create());
        }
예제 #17
0
        private ICode GenerateInternalMethodBody(DependencyInjectionDescriptor descriptor)
        {
            bool hasSubscriptions =
                descriptor.Operations.OfType <SubscriptionOperationDescriptor>().Any();
            bool hasQueries =
                descriptor.Operations.OfType <QueryOperationDescriptor>().Any();
            bool hasMutations =
                descriptor.Operations.OfType <MutationOperationDescriptor>().Any();

            var body = CodeBlockBuilder
                       .New()
                       .AddCode(_staticCode);

            if (hasSubscriptions)
            {
                body.AddCode(RegisterWebSocketConnection(descriptor.Name));
            }

            if (hasQueries || hasMutations)
            {
                body.AddCode(RegisterHttpConnection(descriptor.Name));
            }

            body.AddEmptyLine();

            foreach (var typeDescriptor in descriptor.TypeDescriptors
                     .OfType <INamedTypeDescriptor>())
            {
                if (typeDescriptor.Kind == TypeKind.EntityType && !typeDescriptor.IsInterface())
                {
                    INamedTypeDescriptor namedTypeDescriptor =
                        (INamedTypeDescriptor)typeDescriptor.NamedType();
                    NameString className = namedTypeDescriptor.ExtractMapperName();

                    var interfaceName =
                        TypeNames.IEntityMapper.WithGeneric(
                            namedTypeDescriptor.ExtractTypeName(),
                            typeDescriptor.RuntimeType.Name);

                    body.AddMethodCall()
                    .SetMethodName(TypeNames.AddSingleton)
                    .AddGeneric(interfaceName)
                    .AddGeneric(className)
                    .AddArgument(_services);
                }
            }

            body.AddEmptyLine();

            foreach (var enumType in descriptor.EnumTypeDescriptor)
            {
                body.AddMethodCall()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(TypeNames.ISerializer)
                .AddGeneric(CreateEnumParserName(enumType.Name))
                .AddArgument(_services);
            }

            foreach (var serializer in _serializers)
            {
                body.AddMethodCall()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(TypeNames.ISerializer)
                .AddGeneric(serializer)
                .AddArgument(_services);
            }

            RuntimeTypeInfo stringTypeInfo = TypeInfos.From(TypeNames.String);

            foreach (var scalar in descriptor.TypeDescriptors.OfType <ScalarTypeDescriptor>())
            {
                if (scalar.RuntimeType.Equals(stringTypeInfo) &&
                    scalar.SerializationType.Equals(stringTypeInfo) &&
                    !BuiltInScalarNames.IsBuiltInScalar(scalar.Name))
                {
                    body.AddMethodCall()
                    .SetMethodName(TypeNames.AddSingleton)
                    .AddGeneric(TypeNames.ISerializer)
                    .AddArgument(_services)
                    .AddArgument(MethodCallBuilder
                                 .Inline()
                                 .SetNew()
                                 .SetMethodName(TypeNames.StringSerializer)
                                 .AddArgument(scalar.Name.AsStringToken()));
                }
            }

            foreach (var inputTypeDescriptor in descriptor.TypeDescriptors
                     .Where(x => x.Kind is TypeKind.InputType))
            {
                body.AddMethodCall()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(TypeNames.ISerializer)
                .AddGeneric(CreateInputValueFormatter(
                                (InputObjectTypeDescriptor)inputTypeDescriptor.NamedType()))
                .AddArgument(_services);
            }

            body.AddCode(RegisterSerializerResolver());

            body.AddEmptyLine();

            foreach (var operation in descriptor.Operations)
            {
                if (!(operation.ResultTypeReference is InterfaceTypeDescriptor typeDescriptor))
                {
                    continue;
                }

                string connectionKind = operation is SubscriptionOperationDescriptor
                    ? TypeNames.WebSocketConnection
                    : TypeNames.HttpConnection;
                NameString operationName      = operation.OperationName;
                NameString fullName           = operation.Name;
                NameString operationInterface = typeDescriptor.RuntimeType.Name;

                // The factories are generated based on the concrete result type, which is the
                // only implementee of the result type interface.

                var factoryName =
                    CreateResultFactoryName(
                        typeDescriptor.ImplementedBy.First().RuntimeType.Name);

                var builderName = CreateResultBuilderName(operationName);
                body.AddCode(
                    RegisterOperation(
                        connectionKind,
                        fullName,
                        operationInterface,
                        factoryName,
                        builderName));
            }

            body.AddCode(
                MethodCallBuilder
                .New()
                .SetMethodName(TypeNames.AddSingleton)
                .AddGeneric(descriptor.RuntimeType.Name)
                .AddArgument(_services));

            body.AddLine($"return {_services};");

            return(body);
        }