public virtual ControllerDescriptor Generate(Type grpcServiceType) { string serviceName = grpcServiceType.Name; IReadOnlyList <MethodDescriptor> methods = new ReadOnlyCollection <MethodDescriptor>(grpcServiceType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod).Where(x => x.DeclaringType == grpcServiceType) .Select(GenerateMethodDescriptor).ToList()); ControllerDescriptor controllerDescriptor = new ControllerDescriptor(grpcServiceType, methods) { ServiceName = serviceName, TypeName = serviceName + "Controller" }; controllerDescriptor.CustomAttributes.Add(new AttributeDescriptor { Constructor = typeof(ApiControllerAttribute).GetConstructor(Type.EmptyTypes), ConstructorArgs = _emptyObjectArray }); return(controllerDescriptor); }
public Assembly Compile(ControllerDescriptor controllerDescriptor) { string baseName = controllerDescriptor.ServiceName; Type grpcServiceType = controllerDescriptor.GrpcServiceType; AssemblyBuilder asmBldr = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(baseName), AssemblyBuilderAccess.Run); ModuleBuilder modBldr = asmBldr.DefineDynamicModule(baseName); TypeBuilder typeBuilder = modBldr.DefineType(controllerDescriptor.TypeName, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, controllerDescriptor.BaseType); SetAttributes(controllerDescriptor.CustomAttributes, typeBuilder.SetCustomAttribute); FieldBuilder serviceField = typeBuilder.DefineField("_service", grpcServiceType, FieldAttributes.Private | FieldAttributes.InitOnly); FieldBuilder ctxFactoryField = typeBuilder.DefineField("_ctxFact", typeof(IServerCallContextFactory), FieldAttributes.Private | FieldAttributes.InitOnly); DefineConstructor(typeBuilder, serviceField, ctxFactoryField); foreach (MethodDescriptor md in controllerDescriptor.Methods) { DefineMethod(typeBuilder, md, serviceField, ctxFactoryField); } return(typeBuilder.CreateTypeInfo().Assembly); }