private ServiceEntry Create(MethodInfo method) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var serviceDescriptor = new ServiceDescriptor { Id = serviceId, }; var descriptorAttributes = method.GetCustomAttributes <ServiceDescriptorAttribute>(); foreach (var descriptorAttribute in descriptorAttributes) { descriptorAttribute.Apply(serviceDescriptor); } return(new ServiceEntry { Descriptor = serviceDescriptor, Attributes = method.GetCustomAttributes().ToList(), Func = (key, parameters) => { var instance = _serviceProvider.GetInstances(key, method.DeclaringType); var list = new List <object>(); foreach (var parameterInfo in method.GetParameters()) { var value = parameters[parameterInfo.Name]; var parameterType = parameterInfo.ParameterType; var parameter = _typeConvertibleService.Convert(value, parameterType); list.Add(parameter); } var result = method.Invoke(instance, list.ToArray()); return Task.FromResult(result); } }); }
private ServiceEntry Create(MethodInfo method, string serviceName, string routeTemplate) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var attributes = method.GetCustomAttributes().ToList(); var serviceDescriptor = new ServiceDescriptor { Id = serviceId, RoutePath = RoutePatternParser.Parse(routeTemplate, serviceName, method.Name) }; var descriptorAttributes = method.GetCustomAttributes <ServiceDescriptorAttribute>(); foreach (var descriptorAttribute in descriptorAttributes) { descriptorAttribute.Apply(serviceDescriptor); } var authorization = attributes.Where(p => p is AuthorizationFilterAttribute).FirstOrDefault(); if (authorization != null) { serviceDescriptor.EnableAuthorization(true); } if (authorization != null) { serviceDescriptor.AuthType(((authorization as AuthorizationAttribute)?.AuthType) ?? AuthorizationType.AppSecret); } var fastInvoker = GetHandler(serviceId, method); return(new ServiceEntry { Descriptor = serviceDescriptor, RoutePath = serviceDescriptor.RoutePath, MethodName = method.Name, Type = method.DeclaringType, Attributes = attributes, Func = (key, parameters) => { var instance = _serviceProvider.GetInstances(key, method.DeclaringType); var list = new List <object>(); foreach (var parameterInfo in method.GetParameters()) { //加入是否有默认值的判断,有默认值,并且用户没传,取默认值 if (parameterInfo.HasDefaultValue && !parameters.ContainsKey(parameterInfo.Name)) { list.Add(parameterInfo.DefaultValue); continue; } var value = parameters[parameterInfo.Name]; var parameterType = parameterInfo.ParameterType; var parameter = _typeConvertibleService.Convert(value, parameterType); list.Add(parameter); } var result = fastInvoker(instance, list.ToArray()); return Task.FromResult(result); } }); }
/// <summary> /// 创建服务条目。 /// </summary> /// <param name="service">服务类型。</param> /// <param name="serviceImplementation">服务实现类型。</param> /// <returns>服务条目集合。</returns> public IEnumerable <ServiceEntry> CreateServiceEntry(Type service, Type serviceImplementation) { foreach (var methodInfo in service.GetMethods()) { var implementationMethodInfo = serviceImplementation.GetMethod(methodInfo.Name, methodInfo.GetParameters().Select(p => p.ParameterType).ToArray()); yield return(Create(_serviceIdGenerator.GenerateServiceId(methodInfo), implementationMethodInfo)); } }
public LiveStreamServiceExecutor( IRtmpRemoteInvokeService rtmpRemoteInvokeService, IServiceIdGenerator serviceIdGenerator ) { _rtmpRemoteInvokeService = rtmpRemoteInvokeService; _publishServiceId = serviceIdGenerator.GenerateServiceId(typeof(ILiveRomtePublishService).GetMethod("Publish")); }
public AbstractChannelService(IMessagePushService messagePushService, IMqttBrokerEntryManger mqttBrokerEntryManger, IMqttRemoteInvokeService mqttRemoteInvokeService, IServiceIdGenerator serviceIdGenerator ) { _messagePushService = messagePushService; _mqttBrokerEntryManger = mqttBrokerEntryManger; _mqttRemoteInvokeService = mqttRemoteInvokeService; _publishServiceId = serviceIdGenerator.GenerateServiceId(typeof(IMqttRomtePublishService).GetMethod("Publish")); }
private ServiceEntry Create(MethodInfo method, MethodBase implementationMethod) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var serviceDescriptor = new ServiceDescriptor { Id = serviceId }; var descriptorAttributes = method.GetCustomAttributes <RpcServiceDescriptorAttribute>(); foreach (var descriptorAttribute in descriptorAttributes) { descriptorAttribute.Apply(serviceDescriptor); } return(new ServiceEntry { Descriptor = serviceDescriptor, Func = async(parameters) => { Stopwatch watch = new Stopwatch(); watch.Start(); var serviceScopeFactory = _serviceProvider.GetService <IServiceScopeFactory>(); using (var scope = serviceScopeFactory.CreateScope()) { var instance = scope.ServiceProvider.GetService(method.DeclaringType); var list = new List <object>(implementationMethod.GetParameters().Length); foreach (var parameterInfo in implementationMethod.GetParameters()) { var value = parameters[parameterInfo.Name]; var parameterType = parameterInfo.ParameterType; var parameter = _typeConvertibleService.Convert(value, parameterType); list.Add(parameter); } var result = implementationMethod.Invoke(instance, list.ToArray()); watch.Stop(); _logger.LogInformation($"执行耗时:{watch.ElapsedMilliseconds}/ms"); Task <ActionResult> task = result as Task <ActionResult>; return await task; } } }); }
private ServiceEntry Create(MethodInfo method, MethodReflector implementationMethod) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var serviceDescriptor = new ServiceDescriptor { Id = serviceId }; var descriptorAttributes = method.GetCustomAttributes <RpcServiceDescriptorAttribute>(); foreach (var descriptorAttribute in descriptorAttributes) { descriptorAttribute.Apply(serviceDescriptor); } return(new ServiceEntry { Descriptor = serviceDescriptor, Func = parameters => { var serviceScopeFactory = _serviceProvider.GetRequiredService <IServiceScopeFactory>(); using (var scope = serviceScopeFactory.CreateScope()) { var instance = scope.ServiceProvider.GetRequiredService(method.DeclaringType); var list = new List <object>(); foreach (var parameterInfo in method.GetParameters()) { if (parameterInfo.HasDefaultValue && !parameters.ContainsKey(parameterInfo.Name)) { list.Add(parameterInfo.DefaultValue); continue; } var value = parameters[parameterInfo.Name]; var parameterType = parameterInfo.ParameterType; var parameter = _typeConvertibleService.Convert(value, parameterType); list.Add(parameter); } var result = implementationMethod.Invoke(instance, list.ToArray()); return Task.FromResult(result); } } }); }
private ServiceEntry Create(MethodInfo method, string serviceName, string routeTemplate) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var attributes = method.GetCustomAttributes().ToList(); var serviceDescriptor = new ServiceDescriptor { Id = serviceId, RoutePath = RoutePatternParser.Parse(routeTemplate, serviceName, method.Name) }; return(new ServiceEntry { Descriptor = serviceDescriptor, RoutePath = serviceDescriptor.RoutePath, MethodName = method.Name, Type = method.DeclaringType, Attributes = attributes, }); }
private ServiceEntry Create(MethodInfo method, string serviceName, string routeTemplate) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var attributes = method.GetCustomAttributes().ToList(); var serviceDescriptor = new ServiceDescriptor { Id = serviceId, RoutePath = RoutePatternParser.Parse(routeTemplate, serviceName, method.Name) }; var descriptorAttributes = method.GetCustomAttributes <ServiceDescriptorAttribute>(); foreach (var descriptorAttribute in descriptorAttributes) { descriptorAttribute.Apply(serviceDescriptor); } serviceDescriptor.EnableAuthorization(!serviceDescriptor.EnableAuthorization() ? attributes.Any(p => p is AuthorizationFilterAttribute) : serviceDescriptor.EnableAuthorization()); var fastInvoker = FastInvoke.GetMethodInvoker(method); return(new ServiceEntry { Descriptor = serviceDescriptor, Attributes = attributes, Func = (key, parameters) => { var instance = _serviceProvider.GetInstances(key, method.DeclaringType); var list = new List <object>(); foreach (var parameterInfo in method.GetParameters()) { var value = parameters[parameterInfo.Name]; var parameterType = parameterInfo.ParameterType; var parameter = _typeConvertibleService.Convert(value, parameterType); list.Add(parameter); } var result = fastInvoker(instance, list.ToArray()); //method.Invoke(instance, list.ToArray()); return Task.FromResult(result); } }); }
/// <summary> /// 从容器中实例化对象,并调用对应方法 /// </summary> /// <param name="method"></param> /// <param name="implementationMethod"></param> /// <returns>通过容器实例化ServiceEntity实体进行实例化,并调用相应的方法</returns> private ServiceEntity Create(MethodInfo method, MethodBase implementationMethod) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var serviceDescriptor = new ServiceDescriptor { Id = serviceId }; return(new ServiceEntity { Descriptor = serviceDescriptor, Func = async parameters => { // 从Microsoft.Extensions.DependencyInjection获取当前范围 var serviceScopeFactory = _serviceProvider.GetRequiredService <IServiceScopeFactory>(); if (parameters.Any(p => p.Key.Equals("token"))) { if (!_authorization.ValidateClientAuthentication(parameters.First(l => l.Key.Equals("token")).Value.ToString())) { return Task.FromResult("{\"error\":\"failure token\"}"); } } using (var scope = serviceScopeFactory.CreateScope()) { var par = implementationMethod.GetParameters() .Select(parameterInfo => _typeConvertibleService.Convert(parameters[parameterInfo.Name], parameterInfo.ParameterType)) .ToArray(); var invoke = implementationMethod.Invoke(scope.ServiceProvider.GetRequiredService(method.DeclaringType), par); var fullName = invoke.GetType().FullName; if (fullName != null && fullName.Contains(typeof(Task).FullName ?? throw new InvalidOperationException())) { return Task.FromResult(((dynamic)invoke).Result); } return Task.FromResult(invoke); } } });
public async override Task InterceptAsync(ILmsMethodInvocation invocation) { var servcieId = _serviceIdGenerator.GenerateServiceId(invocation.Method); var serviceEntry = _serviceEntryLocator.GetServiceEntryById(servcieId); try { invocation.ReturnValue = await _serviceExecutor.Execute(serviceEntry, invocation.Arguments, _currentServiceKey.ServiceKey); } catch (Exception e) { if (!e.IsBusinessException() && serviceEntry.FallBackExecutor != null) { await invocation.ProceedAsync(); } else { throw; } } }
// 此方法严重依赖于Microsoft.Extensions.DependencyInjection库,需要拆分 // 通过容器实例化ServiceEntity实体 private ServiceEntity Create(MethodInfo method, MethodBase implementationMethod) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var serviceDescriptor = new ServiceDescriptor { Id = serviceId }; return(new ServiceEntity { Descriptor = serviceDescriptor, Func = parameters => { // 从Microsoft.Extensions.DependencyInjection获取当前范围 var serviceScopeFactory = _serviceProvider.GetRequiredService <IServiceScopeFactory>(); using (var scope = serviceScopeFactory.CreateScope()) { var instance = scope.ServiceProvider.GetRequiredService(method.DeclaringType); var list = new List <object>(); foreach (var parameterInfo in implementationMethod.GetParameters()) { list.Add( _typeConvertibleService.Convert( parameters[parameterInfo.Name], parameterInfo.ParameterType) ); } return Task.FromResult(implementationMethod.Invoke( instance, list.ToArray() )); } } }); }
private MemberDeclarationSyntax GenerateMethodDeclaration(MethodInfo method) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var returnDeclaration = GetTypeSyntax(method.ReturnType); var parameterList = new List <SyntaxNodeOrToken>(); var parameterDeclarationList = new List <SyntaxNodeOrToken>(); foreach (var parameter in method.GetParameters()) { parameterDeclarationList.Add(Parameter( Identifier(parameter.Name)) .WithType(GetQualifiedNameSyntax(parameter.ParameterType))); parameterDeclarationList.Add(Token(SyntaxKind.CommaToken)); parameterList.Add(InitializerExpression( SyntaxKind.ComplexElementInitializerExpression, SeparatedList <ExpressionSyntax>( new SyntaxNodeOrToken[] { LiteralExpression( SyntaxKind.StringLiteralExpression, Literal(parameter.Name)), Token(SyntaxKind.CommaToken), IdentifierName(parameter.Name) }))); parameterList.Add(Token(SyntaxKind.CommaToken)); } if (parameterList.Any()) { parameterList.RemoveAt(parameterList.Count - 1); parameterDeclarationList.RemoveAt(parameterDeclarationList.Count - 1); } var declaration = MethodDeclaration( returnDeclaration, Identifier(method.Name)) .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.AsyncKeyword))) .WithParameterList(ParameterList(SeparatedList <ParameterSyntax>(parameterDeclarationList))); ExpressionSyntax expressionSyntax; StatementSyntax statementSyntax; if (method.ReturnType != typeof(Task)) { expressionSyntax = GenericName( Identifier("Invoke")).WithTypeArgumentList(((GenericNameSyntax)returnDeclaration).TypeArgumentList); } else { expressionSyntax = IdentifierName("Invoke"); } expressionSyntax = AwaitExpression( InvocationExpression(expressionSyntax) .WithArgumentList( ArgumentList( SeparatedList <ArgumentSyntax>( new SyntaxNodeOrToken[] { Argument( ObjectCreationExpression( GenericName( Identifier("Dictionary")) .WithTypeArgumentList( TypeArgumentList( SeparatedList <TypeSyntax>( new SyntaxNodeOrToken[] { PredefinedType( Token(SyntaxKind.StringKeyword)), Token(SyntaxKind.CommaToken), PredefinedType( Token(SyntaxKind.ObjectKeyword)) })))) .WithInitializer( InitializerExpression( SyntaxKind.CollectionInitializerExpression, SeparatedList <ExpressionSyntax>( parameterList)))), Token(SyntaxKind.CommaToken), Argument( LiteralExpression( SyntaxKind.StringLiteralExpression, Literal(serviceId))) })))); if (method.ReturnType != typeof(Task)) { statementSyntax = ReturnStatement(expressionSyntax); } else { statementSyntax = ExpressionStatement(expressionSyntax); } declaration = declaration.WithBody( Block( SingletonList(statementSyntax))); return(declaration); }
private MemberDeclarationSyntax GenerateMethodDeclaration(MethodInfo method) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); TypeSyntax returnDeclaration = GetTypeSyntax(method.ReturnType); var parameterList = new List <SyntaxNodeOrToken>(); var parameterDeclarationList = new List <SyntaxNodeOrToken>(); foreach (var parameter in method.GetParameters()) { parameterDeclarationList.Add(SyntaxFactory.Parameter( SyntaxFactory.Identifier(parameter.Name)) .WithType(GetQualifiedNameSyntax(parameter.ParameterType))); parameterDeclarationList.Add(SyntaxFactory.Token(SyntaxKind.CommaToken)); parameterList.Add( SyntaxFactory.InitializerExpression(SyntaxKind.ComplexElementInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>(new SyntaxNodeOrToken[] { SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(parameter.Name)), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.IdentifierName(parameter.Name) }))); parameterList.Add(SyntaxFactory.Token(SyntaxKind.CommaToken)); } if (parameterList.Any()) { parameterList.RemoveAt(parameterList.Count - 1); parameterDeclarationList.RemoveAt(parameterDeclarationList.Count - 1); } if (!method.Name.Contains("Dispose") && _token != "") { // parameterDeclarationList.Add(SyntaxFactory.Token(SyntaxKind.CommaToken)); // parameterDeclarationList.Add(SyntaxFactory.Parameter( // SyntaxFactory.Identifier("token")) // .WithType(GetQualifiedNameSyntax(typeof(string)))); if (method.GetParameters().Any()) { parameterList.Add(SyntaxFactory.Token(SyntaxKind.CommaToken)); } parameterList.Add( SyntaxFactory.InitializerExpression(SyntaxKind.ComplexElementInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>(new SyntaxNodeOrToken[] { SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("token")), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(_token)) }))); } MethodDeclarationSyntax declaration; if (method.ToString().Contains("Task")) { declaration = SyntaxFactory.MethodDeclaration( returnDeclaration, SyntaxFactory.Identifier(method.Name) ).WithModifiers(SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword)) ).WithParameterList(SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList <ParameterSyntax>(parameterDeclarationList))); } else { if (method.ToString().Contains("Void")) { declaration = SyntaxFactory.MethodDeclaration( SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), SyntaxFactory.Identifier("Dispose") ).WithModifiers( SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))); } else { declaration = SyntaxFactory.MethodDeclaration( returnDeclaration, SyntaxFactory.Identifier(method.Name) ).WithModifiers( SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword) )).WithParameterList( SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList <ParameterSyntax>(parameterDeclarationList))); } } ExpressionSyntax expressionSyntax; StatementSyntax statementSyntax = null; if (method.ReturnType.ToString().Contains("Task")) { expressionSyntax = SyntaxFactory.GenericName(SyntaxFactory.Identifier("InvokeAsync")) .WithTypeArgumentList(((GenericNameSyntax)returnDeclaration).TypeArgumentList); } else { var list = new List <SyntaxNodeOrToken> { GetQualifiedNameSyntax(method.ReturnType.FullName) }; var typeArgumentListSyntax = SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList <TypeSyntax>(list.ToArray())); expressionSyntax = SyntaxFactory.GenericName("Invoke").WithTypeArgumentList(typeArgumentListSyntax); } if (method.ReturnType.ToString().Contains("Task")) { expressionSyntax = SyntaxFactory.AwaitExpression( SyntaxFactory.InvocationExpression(expressionSyntax).WithArgumentList( SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList <ArgumentSyntax>(new SyntaxNodeOrToken[] { SyntaxFactory.Argument( SyntaxFactory.ObjectCreationExpression( SyntaxFactory.GenericName(SyntaxFactory.Identifier("Dictionary")).WithTypeArgumentList( SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList <TypeSyntax>(new SyntaxNodeOrToken[] { SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)), })))).WithInitializer( SyntaxFactory.InitializerExpression(SyntaxKind.CollectionInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>(parameterList)))), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(serviceId))) })))); } else { expressionSyntax = SyntaxFactory.InvocationExpression(expressionSyntax).WithArgumentList( SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList <ArgumentSyntax>(new SyntaxNodeOrToken[] { SyntaxFactory.Argument( SyntaxFactory.ObjectCreationExpression( SyntaxFactory.GenericName(SyntaxFactory.Identifier("Dictionary")) .WithTypeArgumentList( SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList <TypeSyntax>(new SyntaxNodeOrToken[] { SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)) } ) ) ) ) .WithInitializer(SyntaxFactory.InitializerExpression(SyntaxKind.CollectionInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>(parameterList)) ) ), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(serviceId))) } ))); } if (method.ReturnType != typeof(Task)) { if (!method.ToString().Contains("Void")) { statementSyntax = SyntaxFactory.ReturnStatement(expressionSyntax); } } else { statementSyntax = SyntaxFactory.ExpressionStatement(expressionSyntax); } declaration = declaration.WithBody( SyntaxFactory.Block( SyntaxFactory.SingletonList(statementSyntax))); return(declaration); }
public IServiceEntryContainer AddServices(Type[] types) { //var serviceTypes = types.Where(x => //{ // var typeinfo = x.GetTypeInfo(); // return typeinfo.IsInterface && typeinfo.GetCustomAttribute<JimuServiceRouteAttribute>() != null; //}).Distinct(); var serviceTypes = types .Where(x => x.GetMethods().Any(y => y.GetCustomAttribute <JimuServiceAttribute>() != null)).Distinct(); foreach (var type in serviceTypes) { var routeTemplate = type.GetCustomAttribute <JimuServiceRouteAttribute>(); foreach (var methodInfo in type.GetTypeInfo().GetMethods().Where(x => x.GetCustomAttributes <JimuServiceDescAttribute>().Any())) { JimuServiceDesc desc = new JimuServiceDesc(); var descriptorAttributes = methodInfo.GetCustomAttributes <JimuServiceDescAttribute>(); foreach (var attr in descriptorAttributes) { attr.Apply(desc); } desc.ReturnDesc = GetReturnDesc(methodInfo); if (string.IsNullOrEmpty(desc.HttpMethod)) { desc.HttpMethod = GetHttpMethod(methodInfo); } desc.Parameters = _serializer.Serialize <string>(GetParameters(methodInfo)); if (string.IsNullOrEmpty(desc.Id)) { desc.Id = _serviceIdGenerate.GenerateServiceId(methodInfo); } var fastInvoker = GetHandler(desc.Id, methodInfo); if (routeTemplate != null) { desc.RoutePath = JimuServiceRoute.ParseRoutePath(routeTemplate.RouteTemplate, type.Name, methodInfo.Name, methodInfo.GetParameters(), type.IsInterface); } var service = new JimuServiceEntry { Descriptor = desc, Func = (paras, payload) => { var instance = GetInstance(null, methodInfo.DeclaringType, payload); var parameters = new List <object>(); foreach (var para in methodInfo.GetParameters()) { paras.TryGetValue(para.Name, out var value); var paraType = para.ParameterType; var parameter = _typeConvertProvider.Convert(value, paraType); parameters.Add(parameter); } var result = fastInvoker(instance, parameters.ToArray()); return(Task.FromResult(result)); } }; _services.Add(service); } } return(this); }
private ServiceEntry Create(MethodInfo method, string serviceName, string routeTemplate, bool routeIsReWriteByServiceRoute = false) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var attributes = method.GetCustomAttributes().ToList(); var serviceDescriptor = new ServiceDescriptor { Id = serviceId, RoutePath = RoutePatternParser.Parse(routeTemplate, serviceName, method.Name, routeIsReWriteByServiceRoute) }; var httpMethodAttributes = attributes.Where(p => p is HttpMethodAttribute).Select(p => p as HttpMethodAttribute).ToList(); var httpMethods = new List <string>(); foreach (var httpAttribute in httpMethodAttributes) { httpMethods.AddRange(httpAttribute.HttpMethods); } if (!httpMethods.Any()) { var paramTypes = GetParamTypes(method); if (paramTypes.All(p => p.Value.IsValueType || p.Value == typeof(string) || p.Value.IsEnum)) { httpMethods.Add(HttpMethod.GET.ToString()); } else { httpMethods.Add(HttpMethod.POST.ToString()); } } serviceDescriptor.HttpMethod(httpMethods); var authorization = attributes.Where(p => p is AuthorizationFilterAttribute).FirstOrDefault(); if (authorization != null) { serviceDescriptor.EnableAuthorization(true); } if (authorization != null) { serviceDescriptor.AuthType(((authorization as AuthorizationAttribute)?.AuthType) ?? AuthorizationType.AppSecret); } else { serviceDescriptor.EnableAuthorization(true); serviceDescriptor.AuthType(AuthorizationType.JWT); } var descriptorAttributes = method.GetCustomAttributes <ServiceDescriptorAttribute>(); foreach (var descriptorAttribute in descriptorAttributes) { descriptorAttribute.Apply(serviceDescriptor); } var fastInvoker = GetHandler(serviceId, method); return(new ServiceEntry { Descriptor = serviceDescriptor, RoutePath = serviceDescriptor.RoutePath, Methods = httpMethods, MethodName = method.Name, Type = method.DeclaringType, Attributes = attributes, ParamTypes = GetParamTypes(method), CacheKeys = GetCackeKeys(method), Func = (key, parameters) => { object instance = null; if (AppConfig.ServerOptions.IsModulePerLifetimeScope) { instance = _serviceProvider.GetInstancePerLifetimeScope(key, method.DeclaringType); } else { instance = _serviceProvider.GetInstances(key, method.DeclaringType); } var list = new List <object>(); foreach (var parameterInfo in method.GetParameters()) { if (parameters.ContainsKey(parameterInfo.Name)) { var value = parameters[parameterInfo.Name]; var parameterType = parameterInfo.ParameterType; var parameter = _typeConvertibleService.Convert(value, parameterType); list.Add(parameter); } //加入是否有默认值的判断,有默认值,并且用户没传,取默认值 else if (parameterInfo.HasDefaultValue && !parameters.ContainsKey(parameterInfo.Name)) { list.Add(parameterInfo.DefaultValue); } else { list.Add(null); } } var result = fastInvoker(instance, list.ToArray()); return Task.FromResult(result); } }); }
private ServiceEntry Create(MethodInfo method, string serviceName, string routeTemplate) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var attributes = method.GetCustomAttributes().ToList(); var serviceDescriptor = new ServiceDescriptor { Id = serviceId, RoutePath = RoutePatternParser.Parse(routeTemplate, serviceName, method.Name) }; serviceDescriptor = SetPorts(serviceDescriptor); serviceDescriptor.EnableAuthorization(true); serviceDescriptor.AuthType(AuthorizationType.JWT); var descriptorAttributes = method.GetCustomAttributes <ServiceDescriptorAttribute>(); foreach (var descriptorAttribute in descriptorAttributes) { descriptorAttribute.Apply(serviceDescriptor); } //var authorization = attributes.Where(p => p is AuthorizationFilterAttribute).FirstOrDefault(); //if (authorization != null) //{ // serviceDescriptor.EnableAuthorization(true); // serviceDescriptor.AuthType(((authorization as AuthorizationAttribute)?.AuthType) // ?? AuthorizationType.AppSecret); //} var fastInvoker = GetHandler(serviceId, method); return(new ServiceEntry { Descriptor = serviceDescriptor, RoutePath = serviceDescriptor.RoutePath, MethodName = method.Name, Type = method.DeclaringType, Attributes = attributes, Func = (key, parameters) => { var instance = _serviceProvider.GetInstances(key, method.DeclaringType); var list = new List <object>(); foreach (var parameterInfo in method.GetParameters()) { if (parameterInfo.HasDefaultValue && !parameters.ContainsKey(parameterInfo.Name)) { list.Add(parameterInfo.DefaultValue); continue; } var value = parameters[parameterInfo.Name]; var parameterType = parameterInfo.ParameterType; var parameter = _typeConvertibleService.Convert(value, parameterType); list.Add(parameter); } if (parameters.ContainsKey("payload")) { if (RpcContext.GetContext().GetAttachment("payload") == null) { var serializer = ServiceLocator.GetService <ISerializer <string> >(); var payloadString = serializer.Serialize(parameters["payload"], true); RpcContext.GetContext().SetAttachment("payload", payloadString); } } var result = fastInvoker(instance, list.ToArray()); return Task.FromResult(result); } }); }
private MemberDeclarationSyntax GenerateMethodDeclaration(MethodInfo method) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var returnDeclaration = GetTypeSyntax(method.ReturnType); var parameterList = new List <SyntaxNodeOrToken>(); var parameterDeclarationList = new List <SyntaxNodeOrToken>(); foreach (var parameter in method.GetParameters()) { if (parameter.ParameterType.IsGenericType) { parameterDeclarationList.Add(SyntaxFactory.Parameter( SyntaxFactory.Identifier(parameter.Name)) .WithType(GetTypeSyntax(parameter.ParameterType))); } else { parameterDeclarationList.Add(SyntaxFactory.Parameter( SyntaxFactory.Identifier(parameter.Name)) .WithType(GetQualifiedNameSyntax(parameter.ParameterType))); } parameterDeclarationList.Add(SyntaxFactory.Token(SyntaxKind.CommaToken)); parameterList.Add(SyntaxFactory.InitializerExpression( SyntaxKind.ComplexElementInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>( new SyntaxNodeOrToken[] { SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(parameter.Name)), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.IdentifierName(parameter.Name) }))); parameterList.Add(SyntaxFactory.Token(SyntaxKind.CommaToken)); } if (parameterList.Any()) { parameterList.RemoveAt(parameterList.Count - 1); parameterDeclarationList.RemoveAt(parameterDeclarationList.Count - 1); } MethodDeclarationSyntax declaration; if (method.ReturnType == typeof(void)) { declaration = SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), SyntaxFactory.Identifier(method.Name)); } else { declaration = SyntaxFactory.MethodDeclaration( returnDeclaration, SyntaxFactory.Identifier(method.Name)); } if (method.ReturnType.Namespace == typeof(Task).Namespace) { declaration = declaration.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword))); } else { declaration = declaration.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))); } declaration = declaration.WithParameterList(SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList <ParameterSyntax>(parameterDeclarationList))); ExpressionSyntax expressionSyntax; StatementSyntax statementSyntax; if (method.ReturnType.Namespace != typeof(Task).Namespace) { if (method.ReturnType == typeof(void)) { expressionSyntax = SyntaxFactory.IdentifierName("InvokeVoid"); } else { expressionSyntax = SyntaxFactory.GenericName( SyntaxFactory.Identifier("Invoke")) //.WithTypeArgumentList(((GenericNameSyntax)returnDeclaration).TypeArgumentList); .WithTypeArgumentList(SyntaxFactory.TypeArgumentList(SyntaxFactory.SingletonSeparatedList(returnDeclaration))) ; } expressionSyntax = SyntaxFactory.InvocationExpression(expressionSyntax) .WithArgumentList( SyntaxFactory.ArgumentList( SyntaxFactory.SeparatedList <ArgumentSyntax>( new SyntaxNodeOrToken[] { SyntaxFactory.Argument( SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(serviceId))), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.Argument( SyntaxFactory.ObjectCreationExpression( SyntaxFactory.GenericName( SyntaxFactory.Identifier("Dictionary")) .WithTypeArgumentList( SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList <TypeSyntax>( new SyntaxNodeOrToken[] { SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.StringKeyword)), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.ObjectKeyword)) })))) .WithInitializer( SyntaxFactory.InitializerExpression( SyntaxKind.CollectionInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>( parameterList)))) }))); //expressionSyntax = SyntaxFactory.express } else { if (method.ReturnType == typeof(Task)) { expressionSyntax = SyntaxFactory.IdentifierName("InvokeVoidAsync"); } else { expressionSyntax = SyntaxFactory.GenericName( SyntaxFactory.Identifier("InvokeAsync")) .WithTypeArgumentList(((GenericNameSyntax)returnDeclaration).TypeArgumentList); //.WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(returnDeclaration))) } expressionSyntax = SyntaxFactory.AwaitExpression( SyntaxFactory.InvocationExpression(expressionSyntax) .WithArgumentList( SyntaxFactory.ArgumentList( SyntaxFactory.SeparatedList <ArgumentSyntax>( new SyntaxNodeOrToken[] { SyntaxFactory.Argument( SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(serviceId))), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.Argument( SyntaxFactory.ObjectCreationExpression( SyntaxFactory.GenericName( SyntaxFactory.Identifier("Dictionary")) .WithTypeArgumentList( SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList <TypeSyntax>( new SyntaxNodeOrToken[] { SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.StringKeyword)), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.ObjectKeyword)) })))) .WithInitializer( SyntaxFactory.InitializerExpression( SyntaxKind.CollectionInitializerExpression, SyntaxFactory.SeparatedList <ExpressionSyntax>( parameterList)))) })))); } if (method.ReturnType != typeof(Task) && method.ReturnType != typeof(void)) { statementSyntax = SyntaxFactory.ReturnStatement(expressionSyntax); } else { statementSyntax = SyntaxFactory.ExpressionStatement(expressionSyntax); } declaration = declaration.WithBody( SyntaxFactory.Block( SyntaxFactory.SingletonList(statementSyntax))); return(declaration); }
private ServiceEntry Create(MethodInfo method, string serviceName, string routeTemplate) { var serviceId = _serviceIdGenerator.GenerateServiceId(method); var attributes = method.GetCustomAttributes().ToList(); var serviceDescriptor = new ServiceDescriptor { Id = serviceId, RoutePath = RoutePatternParser.Parse(routeTemplate, serviceName, method.Name) }; var httpMethodAttributes = attributes.Where(p => p is HttpMethodAttribute).Select(p => p as HttpMethodAttribute).ToList(); var httpMethods = new List <string>(); StringBuilder httpMethod = new StringBuilder(); foreach (var attribute in httpMethodAttributes) { httpMethods.AddRange(attribute.HttpMethods); if (attribute.IsRegisterMetadata) { httpMethod.AppendJoin(',', attribute.HttpMethods).Append(","); } } if (httpMethod.Length > 0) { httpMethod.Length = httpMethod.Length - 1; serviceDescriptor.HttpMethod(httpMethod.ToString()); } var authorization = attributes.Where(p => p is AuthorizationFilterAttribute).FirstOrDefault(); if (authorization != null) { serviceDescriptor.EnableAuthorization(true); } if (authorization != null) { serviceDescriptor.AuthType(((authorization as AuthorizationAttribute)?.AuthType) ?? AuthorizationType.AppSecret); } else { serviceDescriptor.EnableAuthorization(true); serviceDescriptor.AuthType(AuthorizationType.JWT); } var descriptorAttributes = method.GetCustomAttributes <ServiceDescriptorAttribute>(); foreach (var descriptorAttribute in descriptorAttributes) { descriptorAttribute.Apply(serviceDescriptor); } var fastInvoker = GetHandler(serviceId, method); return(new ServiceEntry { Descriptor = serviceDescriptor, RoutePath = serviceDescriptor.RoutePath, Methods = httpMethods, MethodName = method.Name, Type = method.DeclaringType, Attributes = attributes, Func = (key, parameters) => { object instance = null; if (AppConfig.ServerOptions.IsModulePerLifetimeScope) { instance = _serviceProvider.GetInstancePerLifetimeScope(key, method.DeclaringType); } else { instance = _serviceProvider.GetInstances(key, method.DeclaringType); } var list = new List <object>(); foreach (var parameterInfo in method.GetParameters()) { //加入是否有默认值的判断,有默认值,并且用户没传,取默认值 if (parameterInfo.HasDefaultValue && !parameters.ContainsKey(parameterInfo.Name)) { list.Add(parameterInfo.DefaultValue); continue; } var value = parameters[parameterInfo.Name]; var parameterType = parameterInfo.ParameterType; var parameter = _typeConvertibleService.Convert(value, parameterType); list.Add(parameter); } var result = fastInvoker(instance, list.ToArray()); return Task.FromResult(result); } }); }
public IServiceEntryContainer AddServices(Type[] types) { IEnumerable <Type> serviceTypes = types .Where(x => x.GetMethods().Any(y => y.GetCustomAttribute <ServiceAttribute>() != null)).Distinct(); foreach (Type type in serviceTypes) { ServiceRouteAttribute routeTemplate = type.GetCustomAttribute <ServiceRouteAttribute>(); ServiceVersionAttribute version = type.GetCustomAttribute <ServiceVersionAttribute>(); foreach (MethodInfo methodInfo in type.GetTypeInfo().GetMethods().Where(x => x.GetCustomAttributes <ServiceDescAttribute>().Any())) { ServiceDesc desc = new ServiceDesc(); IEnumerable <ServiceDescAttribute> descriptorAttributes = methodInfo.GetCustomAttributes <ServiceDescAttribute>(); IEnumerable <FilterBaseAttribute> filters = methodInfo.GetCustomAttributes <FilterBaseAttribute>(); foreach (ServiceDescAttribute attr in descriptorAttributes) { attr.Apply(desc); } desc.ReturnDesc = GetReturnDesc(methodInfo); if (string.IsNullOrEmpty(desc.HttpMethod)) { desc.HttpMethod = GetHttpMethod(methodInfo); } desc.Parameters = _serializer.Serialize <string>(GetParameters(methodInfo)); string route = string.Empty; if (routeTemplate != null) { if (version != null && routeTemplate.RouteTemplate.Contains("{version}")) { route = routeTemplate.RouteTemplate.Replace("{version}", version.Version); desc.Version = version.Version; } else { route = routeTemplate.RouteTemplate; } } if (string.IsNullOrEmpty(desc.Id)) { desc.Id = _serviceIdGenerate.GenerateServiceId(methodInfo, route, desc).ToLower(); } FastExecutor.FastExecutorHandler fastInvoker = GetHandler(desc.Id, methodInfo); ParameterInfo[] methodParas = methodInfo.GetParameters(); if (routeTemplate != null) { desc.RoutePath = ServiceRoute.ParseRoutePath(route, type.Name, methodInfo.Name, methodParas, type.IsInterface); } ServiceEntry service = new ServiceEntry { Descriptor = desc, Parameters = methodParas, Func = (context) => { object instance = GetInstance(methodInfo.DeclaringType, context.RemoteInvokeMessage.Payload); Dictionary <Type, object> dic = new Dictionary <Type, object>(); foreach (ParameterInfo p in methodParas) { context.RemoteInvokeMessage.Parameters.TryGetValue(p.Name.ToLower(), out object value); object parameter; Type paraType = p.ParameterType; if (typeof(List <ServerFile>) == paraType) { List <FileData> fileData = _typeConvertProvider.Convert(value, paraType) as List <FileData>; List <ServerFile> files = new List <ServerFile>(); foreach (FileData file in fileData) { ServerFile serverFile = new ServerFile { Data = Convert.FromBase64String(file.Data), FileName = file.FileName }; files.Add(serverFile); } parameter = files; } else { parameter = _typeConvertProvider.Convert(value, paraType) ?? null; } dic[paraType] = parameter; } FilterContext filterContext = new FilterContext() { Payload = context.RemoteInvokeMessage.Payload, Descriptor = desc, ServiceArguments = dic }; filters?.Aggregate(filterContext, (filtercontext, filter) => { filter.Container = _container; if (filtercontext.Result == null) { filter.OnActionExecuting(filtercontext); } return(filtercontext); }); if (filterContext.Result == null) { filterContext.Result = fastInvoker(instance, dic.Select(o => o.Value).ToArray()); filters?.Aggregate(filterContext, (filtercontext, filter) => { filter.OnActionExecuted(filtercontext); return(filtercontext); }); } return(Task.FromResult(filterContext.Result)); } }; _services.Add(service); } } return(this); }