Beispiel #1
0
        /// <summary>
        /// 初始化 Grpc 服务
        /// </summary>
        /// <param name="config">Grpc 配置项</param>
        private void InitializeGrpcServer(IGrpcServerConfiguration config)
        {
            var options = new MagicOnionOptions();

            options.IsReturnExceptionStackTraceInErrorDetail = true;

            var serviceLocator = new CasteWindsorServiceLocatorBridge(IocManager);

            options.ServiceLocator = serviceLocator;

            // 构建 gRpc 服务。
            MagicOnionServiceDefinition serviceDefine = null;

            if (config.GrpcAssemblies != null)
            {
                serviceDefine = MagicOnionEngine.BuildServerServiceDefinition(config.GrpcAssemblies.ToArray(), options);
            }

            // 注入 gRpc 服务到 IoC 容器当中。
            IocManager.IocContainer.Register(Component.For <MagicOnionServiceDefinition>().Instance(serviceDefine).LifestyleSingleton());
            IocManager.IocContainer.Register(Component.For <IHostedService>().Instance(new PackageMagicOnionServerService(serviceDefine, new[]
            {
                new ServerPort(config.GrpcBindAddress, config.GrpcBindPort, ServerCredentials.Insecure)
            }, null)).LifestyleSingleton());

            AsyncHelper.RunSync(() => IocManager.Resolve <IHostedService>().StartAsync(CancellationToken.None));
        }
Beispiel #2
0
        static async Task Main(string[] _)
        {
            //gRPCサーバーのAddress・Port設定
            var serverPort = new ServerPort("localhost", 1234, ServerCredentials.Insecure);

            //ロガーとかの設定
            var magicOnionOptions = new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true)
            {
                //todo:settings
            };

            //サービスクラスの実装が別アセンブリの場合はアセンブリを指定する
            var searchAssembly = new[] { typeof(Sample.MagicOnion.Server.Calculator).Assembly };

            //MagicOnion.Hostingを使用する場合
            {
                await MagicOnionHost.CreateDefaultBuilder()
                .UseMagicOnion(searchAssembly, magicOnionOptions, serverPort)
                .RunConsoleAsync();
            }

            //自前でgRPC.Core.Serverを実行する場合
            {
                var server = new Grpc.Core.Server()
                {
                    Ports    = { serverPort },
                    Services = { MagicOnionEngine.BuildServerServiceDefinition(searchAssembly, magicOnionOptions) }
                };

                server.Start();

                Console.ReadLine();
            }
        }
Beispiel #3
0
        /// <summary>
        /// Initializing the GRPC service
        /// </summary>
        private static GRpcServer InitializeGrpcServer(IApiInfo apiInfo, Assembly[] searchAssemblies)
        {
            var option = new MagicOnionOptions
            {
#if DEBUG
                IsReturnExceptionStackTraceInErrorDetail = true
#else
                IsReturnExceptionStackTraceInErrorDetail = false
#endif
            };

            if (searchAssemblies == null)
            {
                searchAssemblies = new[]
                {
                    Assembly.GetEntryAssembly(),
                };
            }

            var grpcServer = new GRpcServer
            {
                Ports    = { new ServerPort(apiInfo.BindAddress, apiInfo.BindPort, ServerCredentials.Insecure) },
                Services =
                {
                    MagicOnionEngine.BuildServerServiceDefinition(
                        searchAssemblies, option)
                }
            };

            grpcServer.Start();
            return(grpcServer);
        }
    }
        static void Main(string[] args)
        {
            GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());

            var type = ServiceGenerator.GenerateService(typeof(MyFirstServiceBase), typeof(InternalServiceRealization));

            MessagePack.MessagePackSerializer.SetDefaultResolver(MessagePack.Resolvers.TypelessContractlessStandardResolver.Instance);
            // setup MagicOnion and option.
            var service = MagicOnionEngine.BuildServerServiceDefinition(new[] { type },
                                                                        new MagicOnionOptions(true)
            {
                FormatterResolver = MessagePack.Resolvers.TypelessContractlessStandardResolver.Instance
            });

            var server = new Grpc.Core.Server
            {
                Services = { service },
                Ports    = { new ServerPort("localhost", 12345, ServerCredentials.Insecure) }
            };

            // launch gRPC Server.
            server.Start();

            Console.WriteLine("Started");
            // and wait.
            Console.ReadLine();
        }
Beispiel #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //这代码跟咱们之前定义服务的那个代码一个样子
            var service = MagicOnionEngine.BuildServerServiceDefinition(new MagicOnionOptions(true)
            {
                MagicOnionLogger = new MagicOnionLogToGrpcLogger()
            });
            var server = new Server
            {
                Services = { service },
                Ports    = { new ServerPort("localhost", 8800, ServerCredentials.Insecure) }
            };

            //这里开始不同,你要把注释生成到xml里给swagger,这里是swagger的用法,看不懂去学swagger
            services.AddSwaggerGen(c =>
            {
                var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Swagger.xml");
                c.IncludeXmlComments(filePath);
            });

            server.Start();

            //这里添加服务
            services.Add(new ServiceDescriptor(typeof(MagicOnionServiceDefinition), service));
            services.AddMvc();
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            //gRPCサーバーのAddress・Port設定
            var serverPort = new ServerPort("localhost", 1234, ServerCredentials.Insecure);

            //ロガーとかの設定
            var magicOnionOptions = new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true)
            {
                //todo:settings
            };

            //サービスクラスの実装が別アセンブリの場合はアセンブリを指定する
            var searchAssembly = new[] { typeof(Sample.MagicOnion.Server.Calculator).Assembly };


            var server = new Grpc.Core.Server()
            {
                Ports    = { serverPort },
                Services =
                {
                    //MagicOnionサービス
                    MagicOnionEngine.BuildServerServiceDefinition(searchAssembly,                             magicOnionOptions),

                    //PureGrpcサービス
                    PureGrpc.Definitions.Calculator.BindService(new Sample.PureGrpc.Server.CalculatorImpl()),
                    PureGrpc.Definitions.Health.BindService(new Sample.PureGrpc.Server.HealthImpl()),
                }
            };

            server.Start();

            Console.ReadLine();
        }
Beispiel #7
0
        public void Start()
        {
            if (!this._initialized)
            {
                this._initialized = true;

                // IServiceProvider の準備
                var serviceCollection = new ServiceCollection();
                this.ConfigureServices(serviceCollection);
                this._serviceProvider = serviceCollection.BuildServiceProvider();

                var service = MagicOnionEngine.BuildServerServiceDefinition(
                    new[] { this._serviceType },
                    new MagicOnionOptions(true)
                {
                    FormatterResolver = WhcFormatterResolver.Instance,
                    GlobalFilters     = new MagicOnionFilterAttribute[]
                    {
                        new DependencyInjectionFilterAttribute(this._serviceProvider),
                    },
                }
                    );

                this._server.Services.Add(service);
            }

            this._server.Start();
        }
        public override void OnApplicationInitialization(CafApplicationContext context)
        {
            var options = new MagicOnionOptions();

            options.IsReturnExceptionStackTraceInErrorDetail = true;
            options.ServiceLocator             = new MicrosoftExtensionsServiceLocator(context.ServiceProvider, options);//new ServiceLocatorBridge(factory);
            options.MagicOnionServiceActivator = new MicrosoftExtensionsMagicOnionServiceActivator();
            MagicOnionServiceDefinition serviceDefine = null;
            var config    = context.ServiceProvider.GetRequiredService <IGrpcServerConfiguration>();
            var generator = context.ServiceProvider.GetRequiredService <IGrpcServiceGenerator>();

            generator.GeneraterProxyService();//创建MagicOnion grpc 代理程序集
            config.GrpcAssemblies = config.GrpcAssemblies.Append(generator.DynamicAssembly).ToList();
            config.GrpcAssemblies = config.GrpcAssemblies.Append(generator.DynamicInterfaceAssembly).ToList();
            if (config.GrpcAssemblies != null)
            {
                serviceDefine = MagicOnionEngine.BuildServerServiceDefinition(config.GrpcAssemblies.ToArray(), options);
            }
            var packageMagicOnionServerService = new PackageMagicOnionServerService(serviceDefine, new[]
            {
                new ServerPort(config.GrpcBindAddress, config.GrpcBindPort, ServerCredentials.Insecure)
            }, null);

            packageMagicOnionServerService.StartAsync(CancellationToken.None);
        }
        public static IMagicOnionServerBuilder AddMagicOnion(this IServiceCollection services, IEnumerable <Type> searchTypes, Action <MagicOnionOptions>?configureOptions = null)
        {
            var configName = Options.Options.DefaultName;

            services.AddSingleton <MagicOnionServiceDefinition>(sp => MagicOnionEngine.BuildServerServiceDefinition(sp, searchTypes, sp.GetRequiredService <IOptionsMonitor <MagicOnionOptions> >().Get(configName)));
            return(services.AddMagicOnionCore(configureOptions));
        }
Beispiel #10
0
        public GRPCServerBuilder Build(GRPCServerOptions options)
        {
            if (options.IsNull())
            {
                throw new MicroAngels.Core.AngleExceptions("GRPC Server Options can't be null");
            }
            if (options.Host.IsNullOrEmpty())
            {
                throw new MicroAngels.Core.AngleExceptions("GRPC Server host is required");
            }
            if (options.Port <= 0)
            {
                throw new MicroAngels.Core.AngleExceptions("GRPC Server port is required");
            }

            MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(new MagicOnionOptions
            {
                MagicOnionLogger = new MagicOnionLogToGrpcLogger()
            });

            var server = new Grpc.Core.Server
            {
                Services = { service },
                Ports    = { new ServerPort(
                                 options.Host,
                                 options.Port,
                                 ServerCredentials.Insecure
                                 ) }
            };

            server.Start();

            return(this);
        }
Beispiel #11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            #region 注册Grpc
            //通过反射去拿
            MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(
                new[] { typeof(ITest).Assembly },   //如果实现的服务层在另一个程序集,需添加此项
                new MagicOnionOptions(true)
            {
                MagicOnionLogger = new MagicOnionLogToGrpcLogger()
            }
                );

            var    serverAddress = this.Configuration["Service:LocalIPAddress"];
            var    serverPort    = Convert.ToInt32(this.Configuration["Service:Port"]);
            Server server        = new Server
            {
                Services = { service },
                Ports    =
                {
                    new ServerPort(serverAddress, serverPort, ServerCredentials.Insecure)//读取配置文件
                }
            };
            server.Start();
            #endregion
        }
Beispiel #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            //添加服务
            var service = MagicOnionEngine.BuildServerServiceDefinition(new MagicOnionOptions(true)
            {
                MagicOnionLogger = new MagicOnionLogToGrpcLogger()
            });

            var server = new Server
            {
                Services = { service },
                Ports    = { new ServerPort("202.135.136.193", 8800, ServerCredentials.Insecure) }
            };

            services.AddSwaggerGen(c =>
            {
                var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Swagger.xml");
                c.IncludeXmlComments(filePath);
            });

            server.Start();

            //添加服务
            services.Add(new ServiceDescriptor(typeof(MagicOnionServiceDefinition), service));
            services.AddMvc();
        }
Beispiel #13
0
        static void Main(string[] args)
        {
            Console.WriteLine("启动服务器...");
            //コンソールにログを表示させる
            GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());

            var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);

            var serverPort = new ServerPort("localhost", 12345, ServerCredentials.Insecure);

            // localhost:12345でListen
            var server = new Server
            {
                Services = { service },
                Ports    = { serverPort }
            };

            // MagicOnion起動
            server.Start();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"启动完成... {serverPort.Host}:{serverPort.Port}");
            Console.ForegroundColor = ConsoleColor.White;

            // コンソールアプリが落ちないようにReadLineで待つ
            Console.ReadLine();
        }
Beispiel #14
0
        static async Task Main(string[] args)
        {
            GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());


            //// you can use new HostBuilder() instead of CreateDefaultBuilder
            await new HostBuilder()
            .UseMagicOnion()
            .RunConsoleAsync();


            //MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(

            //    new[] { typeof(IMyFirstService).Assembly },  // 加载引用程序集
            //    new MagicOnionOptions(true)
            //    {
            //        MagicOnionLogger = new MagicOnionLogToGrpcLogger()
            //    }
            //);

            // setup MagicOnion and option.
            var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);

            var server = new global::Grpc.Core.Server
            {
                Services = { service },
                Ports    = { new ServerPort("localhost", 12345, ServerCredentials.Insecure) }
            };

            // launch gRPC Server.
            server.Start();

            // and wait.
            Console.ReadLine();
        }
        private static GRpcServer InitializeGrpcServer(Uri addresses)
        {
            var grpcServer = new GRpcServer
            {
                Ports    = { new ServerPort(addresses.Host, addresses.Port, ServerCredentials.Insecure) },
                Services = { MagicOnionEngine.BuildServerServiceDefinition() }
            };

            grpcServer.Start();
            return(grpcServer);
        }
        private static GRpcServer InitializeGrpcServer(RpcEndpointOptions options)
        {
            var grpcServer = new GRpcServer
            {
                Ports    = { new ServerPort(options.Address, options.Port, ServerCredentials.Insecure) },
                Services = { MagicOnionEngine.BuildServerServiceDefinition() }
            };

            grpcServer.Start();
            return(grpcServer);
        }
Beispiel #17
0
        private static void Main()
        {
            var service = MagicOnionEngine.BuildServerServiceDefinition();
            var port    = new ServerPort("localhost", 12345, ServerCredentials.Insecure);
            var server  = new Server {
                Services = { service }, Ports = { port }
            };

            server.Start();

            Console.ReadLine();
        }
Beispiel #18
0
        public static void AddREstateToExisting(Server server)
        {
            var service = MagicOnionEngine.BuildServerServiceDefinition(
                targetTypes: new[]
            {
                typeof(StateMachineService)
            },
                option: new MagicOnionOptions(
                    isReturnExceptionStackTraceInErrorDetail: true));

            server.Services.Add(service);
        }
Beispiel #19
0
        public void CanBuildServerServiceDefinition()
        {
            var service = MagicOnionEngine.BuildServerServiceDefinition(
                targetTypes: new[]
            {
                typeof(StateMachineService)
            },
                option: new MagicOnionOptions(
                    isReturnExceptionStackTraceInErrorDetail: true));

            Assert.NotNull(service);
        }
Beispiel #20
0
    static void Main()
    {
        GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());
        var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);
        var server  = new global::Grpc.Core.Server
        {
            Services = { service },
            Ports    = { new ServerPort("localhost", 12345, ServerCredentials.Insecure) }
        };

        server.Start();
        Console.ReadLine();
    }
        public static Grpc.Core.Server InitializeGRpcServer(string host, int port)
        {
            var server = new Grpc.Core.Server
            {
                Ports    = { new ServerPort(host, port, ServerCredentials.Insecure) },
                Services =
                {
                    MagicOnionEngine.BuildServerServiceDefinition()
                }
            };

            server.Start();
            return(server);
        }
Beispiel #22
0
        public static Server StartServer(this ServerPort serverPort)
        {
            var options = new MagicOnionOptions {
                IsReturnExceptionStackTraceInErrorDetail = true
            };
            var service = MagicOnionEngine.BuildServerServiceDefinition(new[] { typeof(ReactiveLoggerHubService).GetTypeInfo().Assembly }, options);
            var server  = new Server {
                Services = { service.ServerServiceDefinition },
                Ports    = { serverPort }
            };

            server.Start();
            return(server);
        }
Beispiel #23
0
        /// <summary>
        /// Initializing the GRPC service
        /// </summary>
        /// <param name="config">Grpc setting</param>
        private static GRpcServer InitializeGrpcServer(IApiInfo apiInfo)
        {
            var grpcServer = new GRpcServer
            {
                Ports    = { new ServerPort(apiInfo.BindAddress, apiInfo.BindPort, ServerCredentials.Insecure) },
                Services =
                {
                    MagicOnionEngine.BuildServerServiceDefinition()
                }
            };

            grpcServer.Start();
            return(grpcServer);
        }
Beispiel #24
0
        /// <summary>
        /// 初始化 Grpc 服务
        /// </summary>
        /// <param name="config">Grpc 配置项</param>
        private void InitializeGrpcServer(IGrpcServerConfiguration config)
        {
            _grpcServer = new GrpcServer
            {
                Ports    = { new ServerPort(config.GrpcBindAddress, config.GrpcBindPort, ServerCredentials.Insecure) },
                Services =
                {
                    MagicOnionEngine.BuildServerServiceDefinition(config.GrpcAssemblies.ToArray(),
                                                                  new MagicOnionOptions(true))
                }
            };

            _grpcServer.Start();
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            Console.WriteLine("RPC服务端已启动。。。");

            var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);
            var server  = new global::Grpc.Core.Server
            {
                Services = { service },
                Ports    = { new ServerPort("localhost", 19021, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.ReadLine();
        }
        /// <summary>
        /// <para>add MagicOnion service to generic host with specific types or assemblies</para>
        /// </summary>
        /// <remarks>you must not pass null to options</remarks>
        public static IHostBuilder UseMagicOnion(this IHostBuilder hostBuilder,
                                                 IEnumerable <ServerPort> ports,
                                                 MagicOnionOptions options,
                                                 IEnumerable <Type> types    = null,
                                                 Assembly[] searchAssemblies = null,
                                                 IEnumerable <ChannelOption> channelOptions = null)
        {
            return(hostBuilder.ConfigureServices((ctx, services) =>
            {
                var serviceLocator = new ServiceLocatorBridge(services);
                options.ServiceLocator = serviceLocator; // replace it.

                // build immediately(require register service before create it).
                MagicOnionServiceDefinition serviceDefinition;
                if (searchAssemblies != null)
                {
                    serviceDefinition = MagicOnionEngine.BuildServerServiceDefinition(searchAssemblies, options);
                }
                else if (types != null)
                {
                    serviceDefinition = MagicOnionEngine.BuildServerServiceDefinition(types, options);
                }
                else
                {
                    if (options != null)
                    {
                        serviceDefinition = MagicOnionEngine.BuildServerServiceDefinition(options);
                    }
                    else
                    {
                        serviceDefinition = MagicOnionEngine.BuildServerServiceDefinition();
                    }
                }

                // store service definition
                services.AddSingleton <MagicOnionServiceDefinition>(serviceDefinition);

                // should transient or singleton?
                // in AddHostedService<T> implementation, singleton is used
                // https://github.com/aspnet/Extensions/blob/8b2482fa68c548e904e4aa1ae38a29c72dcd32a5/src/Hosting/Abstractions/src/ServiceCollectionHostedServiceExtensions.cs#L18
                services.AddSingleton <IHostedService, MagicOnionServerService>(serviceProvider =>
                {
                    serviceLocator.provider = serviceProvider; // set built provider.

                    return new MagicOnionServerService(serviceDefinition, ports, channelOptions);
                });
            }));
        }
Beispiel #27
0
        private static void StartgRPC()
        {
            GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());

            // setup MagicOnion and option.
            var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);

            var server = new Server
            {
                Services = { service },
                Ports    = { new ServerPort("localhost", 12345, ServerCredentials.Insecure) }
            };

            // launch gRPC Server.
            server.Start();
        }
Beispiel #28
0
        /// <summary>
        /// Grpcサーバー開始
        /// </summary>
        /// <returns></returns>
        private bool GrpcServerStart()
        {
            GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());

            var service = MagicOnionEngine.BuildServerServiceDefinition(isReturnExceptionStackTraceInErrorDetail: true);

            var server = new Grpc.Core.Server
            {
                Services = { service },
                Ports    = { new ServerPort("localhost", 12345, ServerCredentials.Insecure) },
            };

            server.Start();

            return(true);
        }
Beispiel #29
0
        static void Main(string[] args)
        {
            GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger());

            var service = MagicOnionEngine.BuildServerServiceDefinition(true);
            var server  = new Grpc.Core.Server()
            {
                Services = { service },
                Ports    = { new ServerPort("localhost", 9000, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.WriteLine("ServerStarted");
            Console.ReadLine();
        }
Beispiel #30
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvcWithDefaultRoute();

            lifetime.ApplicationStarted.Register(() => {
                var service = MagicOnionEngine.BuildServerServiceDefinition(new[] { typeof(Startup).Assembly }, new MagicOnionOptions(true)
                {
                    // MagicOnionLogger = new MagicOnionLogToGrpcLogger(),
                    MagicOnionLogger = new MagicOnionLogToGrpcLoggerWithNamedDataDump(),
                    GlobalFilters    = new MagicOnionFilterAttribute[]
                    {
                    },
                    EnableCurrentContext = true
                });

                var server = new global::Grpc.Core.Server {
                    Services = { service },
                    Ports    = { new ServerPort("0.0.0.0", 12345, ServerCredentials.Insecure) }
                };

                server.Start();

                IConsulClient consul = new ConsulClient(r => {
                    r.Address = new Uri("http://10.10.10.45:8500");
                });

                consul.Agent.ServiceRegister(new AgentServiceRegistration {
                    ID      = "1111",
                    Address = "10.10.10.91",
                    Port    = 12345,
                    Tags    = new[] { "grpc" },
                    Name    = "DemoServer",
                    Check   = new AgentServiceCheck {
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
                        Interval = TimeSpan.FromSeconds(10),
                        Status   = HealthStatus.Passing,
                        Timeout  = TimeSpan.FromSeconds(5),
                        HTTP     = $"http://10.10.10.91:20000/home"
                    }
                }).Wait();
            });
        }