コード例 #1
0
        public static async Task Main(string[] args)
        {
            var ip   = UtilsLibrary.NetworkUtils.GetMyIp();
            int port = int.Parse(ConfigurationManager.AppSettings.Get("port"));

            var reflectionServiceImpl = new ReflectionServiceImpl(ServersListMaker.Descriptor, ServerReflection.Descriptor);

            Grpc.Core.Server server = new Grpc.Core.Server
            {
                Services =
                {
                    ServersListMaker.BindService(new ServersListMakerService()),                     //для сервиса устанвливаем обработчик
                    ServerReflection.BindService(reflectionServiceImpl)
                },
                Ports = { new ServerPort(ip.ToString(), port, ServerCredentials.Insecure) }
            };
            server.Start();

            Console.WriteLine($"Сервер запущен по адресу {ip}:{port}");
            Console.WriteLine("Нажмите любую клавишу для выхода");
            Console.ReadKey();
            Console.WriteLine("Сервер завершает работу");
            await server.ShutdownAsync();

            Console.WriteLine("Сервер закрыт");
            Console.ReadKey();
        }
コード例 #2
0
        static async Task Main(string[] args)
        {
            Server server = null;

            try
            {
                // reflection-1
                var reflectionServiceImpl = new ReflectionServiceImpl(
                    GreetingService.Descriptor
                    , CalculatorService.Descriptor
                    , PrimeNumberDecompositionService.Descriptor
                    , SqrtService.Descriptor
                    , DeadlineService.Descriptor
                    , ServerReflection.Descriptor
                    );

                server = new Server
                {
                    Services =
                    {
                        GreetingService.BindService(new GreetingServiceImplementation()),
                        CalculatorService.BindService(new CalculatorServiceImplementation()),
                        PrimeNumberDecompositionService.BindService(new PrimeNumberDecompositionServiceImplementation()),

                        // errors
                        SqrtService.BindService(new SqrtServiceImplementation()),
                        // deadlines
                        DeadlineService.BindService(new DeadlineServiceImplementation()),

                        // reflection-2
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports =
                    {
                        await CreateUnsecureServerPort(Host, Port)
                    }
                };

                server.Start();
                Console.WriteLine($"Server is listening on {Port}");
                Console.ReadLine();
            }
            catch (IOException ex)
            {
                Console.WriteLine($"Server failed to start: {ex.Message}");
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Server failed: {ex.Message}");
                throw;
            }
            finally
            {
                if (server != null)
                {
                    await server.ShutdownAsync();
                }
            }
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: MohsenZanganeh/grpc-Csharp
        static void Main(string[] args)
        {
            Server server = null;

            try
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(BlogService.Descriptor, ServerReflection.Descriptor);

                server = new Server()
                {
                    Services =
                    {
                        BlogService.BindService(new BlogServiceImpl()),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
                };
                server.Start();
                Console.WriteLine("The server is listenin on port " + port);
                Console.ReadKey();
            }
            catch (IOException e)
            {
                Console.WriteLine("The server faild" + e.Message);
                throw;
            }
            finally
            {
                if (server != null)
                {
                    server.ShutdownAsync().Wait();
                }
            }
        }
コード例 #4
0
        private static void RunServer(Options options)
        {
            var hostName = options.Hostname ?? Dns.GetHostName();

            var serviceDescriptors = new [] { Dlink.Descriptor, Health.Descriptor, ServerReflection.Descriptor };
            var greeterImpl        = new DlinkImpl(hostName);
            var healthServiceImpl  = new HealthServiceImpl();
            var reflectionImpl     = new ReflectionServiceImpl(serviceDescriptors);

            Server server = new Server
            {
                Services = { Dlink.BindService(greeterImpl), Health.BindService(healthServiceImpl), ServerReflection.BindService(reflectionImpl) },
                Ports    = { new ServerPort("[::]", options.Port, ServerCredentials.Insecure) }
            };

            server.Start();

            // Mark all services as healthy.
            foreach (var serviceDescriptor in serviceDescriptors)
            {
                healthServiceImpl.SetStatus(serviceDescriptor.FullName, HealthCheckResponse.Types.ServingStatus.Serving);
            }
            // Mark overall server status as healthy.
            healthServiceImpl.SetStatus("", HealthCheckResponse.Types.ServingStatus.Serving);

            Console.WriteLine("Dlink server listening on port " + options.Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
コード例 #5
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(Task.CompletedTask);
            }

            var descriptors = new List <Google.Protobuf.Reflection.ServiceDescriptor>
            {
                ServerReflection.Descriptor
            };

            foreach (var grpcService in _services)
            {
                _server.Services.Add(grpcService.BindService());
                if (grpcService.Descriptor != null)
                {
                    descriptors.Add(grpcService.Descriptor);
                }
            }

            var reflectionServiceImpl = new ReflectionServiceImpl(descriptors);

            _server.Services.Add(ServerReflection.BindService(reflectionServiceImpl));
            var host = _configuration.GetValue("GrpcHost", "localhost");
            var port = _configuration.GetValue("GrpcPort", 50050);

            _server.Ports.Add(host, port, ServerCredentials.Insecure);
            _server.Start();

            return(Task.CompletedTask);
        }
コード例 #6
0
        public GrpcTestEventHost(ApplicationConfiguration configuration)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            _builder       = new HostBuilder();

            _builder.ConfigureServices(services =>
            {
                services.AddGrpc();
            });
            var stuff = _builder.ConfigureServices((hostContext, services) =>
            {
                // setup the reflection support for service discovery
                var reflectionService = new ReflectionServiceImpl(TestEvent.Descriptor, ServerReflection.Descriptor);
                var testEventService  = new TestEventService(_configuration);
                testEventService.TestEventReceived += TestEventService_TestEventReceived;
                // create a Grpc server
                var server = new Server
                {
                    Services = { TestEvent.BindService(testEventService), ServerReflection.BindService(reflectionService) },
                    Ports    = { new ServerPort(GrpcServer, _configuration.Port, ServerCredentials.Insecure) },
                };
                var gprcHostedService = new GrpcHostedService(server);
                services.AddSingleton(server);
                services.AddSingleton(gprcHostedService);
                services.AddSingleton <IHostedService, GrpcHostedService>(serviceProvider => gprcHostedService);
                _serviceProvider = services.BuildServiceProvider();
            });
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: henrikklarup/ProtoHub
 static void Main(string[] args)
 {
     try
     {
         var    reflectionServiceImpl = new ReflectionServiceImpl(ProtoHubService.Descriptor, ServerReflection.Descriptor);
         Server server = new Server
         {
             Services =
             {
                 ServerReflection.BindService(reflectionServiceImpl),
                 ProtoHubService.BindService(new ProtoHubImpl())
             },
             Ports = { new ServerPort("localhost", 5000, ServerCredentials.Insecure) }
         };
         server.Start();
         Console.WriteLine("Server listening on port " + 5000);
         Console.WriteLine("Press any key to stop the server...");
         Console.ReadKey();
         server.ShutdownAsync().Wait();
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Exception encountered: {ex}");
     }
 }
コード例 #8
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();

            Configuration = builder.Build();

            var loggerFactory = new LoggerFactory()
                                .AddConsole()
                                .AddDebug();

            ILogger logger    = loggerFactory.CreateLogger <Program>();
            var     rpcLogger = loggerFactory.CreateLogger <InventoryManagementImpl>();

            var port = int.Parse(Configuration["service:port"]);

            var          brokerList    = Configuration["kafkaclient:brokerlist"];
            const string ReservedTopic = "inventoryreserved";
            const string ReleasedTopic = "inventoryreleased";

            var config = new Dictionary <string, object>
            {
                { "group.id", "inventory-server" },
                { "enable.auto.commit", false },
                { "bootstrap.servers", brokerList }
            };
            //var context = new InventoryContext(Configuration["postgres:connectionstring"]);
            var context = new InventoryContext();
            var repo    = new InventoryRepository(context);

            var reservedEventProcessor = new InventoryReservedEventProcessor(repo);
            var kafkaConsumer          = new KafkaReservedConsumer(ReservedTopic, config, reservedEventProcessor);

            kafkaConsumer.Consume();

            var releasedEventProcessor = new InventoryReleasedEventProcessor(repo);
            var releasedConsumer       = new KafkaReleasedConsumer(ReleasedTopic, config, releasedEventProcessor);

            releasedConsumer.Consume();

            var refImpl = new ReflectionServiceImpl(
                ServerReflection.Descriptor, InventoryManagement.Descriptor);
            var inventoryManagement = new InventoryManagementImpl(repo, rpcLogger);
            var server = new Server
            {
                Services = { InventoryManagement.BindService(inventoryManagement),
                             ServerReflection.BindService(refImpl) },
                Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
            };

            server.Start();
            logger.LogInformation("Inventory gRPC Service Listening on Port " + port);

            mre.WaitOne();
        }
コード例 #9
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();

            Configuration = builder.Build();

            var loggerFactory = new LoggerFactory()
                                .AddConsole()
                                .AddDebug();

            ILogger logger = loggerFactory.CreateLogger <Program>();

            var port = int.Parse(Configuration["service:port"]);

            var brokerList = Configuration["kafkaclient:brokerlist"];
            var config     = new Dictionary <string, object>
            {
                { "group.id", "order-command" },
                { "enable.auto.commit", "false" },
                { "bootstrap.servers", brokerList }
            };

            IEventEmitter kafkaEmitter = new KafkaEventEmitter(config, loggerFactory.CreateLogger <KafkaEventEmitter>());
            // TODO: this channel needs to use a service-discovery hostname
            var orderChannel = new Channel($"{Configuration["orderclient:hostname"]}:{Configuration["orderclient:port"]}",
                                           ChannelCredentials.Insecure);
            var inventoryChannel = new Channel($"{Configuration["inventoryclient:hostname"]}:{Configuration["inventoryclient:port"]}",
                                               ChannelCredentials.Insecure);

            logger.LogInformation($"Configured gRPC channel for Order Management client: {orderChannel.ResolvedTarget}");
            logger.LogInformation($"Configured gRPC channel for Inventory Management client: {inventoryChannel.ResolvedTarget}");

            var orderClient     = new OrderManagement.OrderManagementClient(orderChannel);
            var inventoryClient = new InventoryManagement.InventoryManagementClient(inventoryChannel);

            var refImpl = new ReflectionServiceImpl(
                ServerReflection.Descriptor, OrderCommand.Descriptor);

            var rpcLogger = loggerFactory.CreateLogger <OrderCommandImpl>();
            var server    = new Server
            {
                Services = { OrderCommand.BindService(new OrderCommandImpl(rpcLogger, kafkaEmitter, orderClient, inventoryClient)),
                             ServerReflection.BindService(refImpl) },
                Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
            };

            server.Start();

            logger.LogInformation("Orders Command gRPC Service Listening on Port " + port);

            // Keep the process alive without consuming CPU cycles
            mre.WaitOne();
        }
コード例 #10
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();


            Configuration = builder.Build();

            Microsoft.Extensions.Logging.ILoggerFactory loggerFactory = new LoggerFactory()
                                                                        .AddConsole()
                                                                        .AddDebug();

            ILogger logger = loggerFactory.CreateLogger <Program>();

            string       brokerList    = Configuration["kafkaclient:brokerlist"];
            const string Topic         = "orders";
            const string CanceledTopic = "canceledorders";

            var config = new Dictionary <string, object>
            {
                { "group.id", "order-management" },
                { "enable.auto.commit", false },
                { "bootstrap.servers", brokerList }
            };

            var context           = new OrdersContext(Configuration["postgres:connectionstring"]);
            var repo              = new OrderRepository(context);
            var eventProcessor    = new OrderAcceptedEventProcessor(repo);
            var canceledProcessor = new OrderCanceledEventProcessor(repo);

            var orderConsumer    = new KafkaOrdersConsumer(Topic, config, eventProcessor);
            var activityConsumer = new KafkaActivitiesConsumer(CanceledTopic, config, canceledProcessor);

            orderConsumer.Consume();
            activityConsumer.Consume();

            var port = int.Parse(Configuration["service:port"]);

            var refImpl = new ReflectionServiceImpl(
                ServerReflection.Descriptor, OrderManagement.Descriptor);
            Server server = new Server
            {
                Services = { OrderManagement.BindService(new OrderManagementImpl(repo)),
                             ServerReflection.BindService(refImpl) },
                Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
            };

            server.Start();
            logger.LogInformation("Order management gRPC service listening on port " + port);

            mre.WaitOne();
        }
コード例 #11
0
        static void Main(string[] args)
        {
            Server server = null;

            try
            {
                var serverCertificate  = File.ReadAllText("ssl/server.crt");
                var serverKey          = File.ReadAllText("ssl/server.key");
                var keyCertificatePair = new KeyCertificatePair(serverCertificate, serverKey);
                var caCertificate      = File.ReadAllText("ssl/ca.crt");

                var credentials = new SslServerCredentials(new List <KeyCertificatePair>()
                {
                    keyCertificatePair
                }, caCertificate, true);

                // ./evans.exe -r -p 50051
                var greetingServiceReflectionServiceImpl   = new ReflectionServiceImpl(GreetingService.Descriptor, ServerReflection.Descriptor);
                var calculatorServiceReflectionServiceImpl = new ReflectionServiceImpl(CalculatorService.Descriptor, ServerReflection.Descriptor);
                var blogServiceReflectionServiceImpl       = new ReflectionServiceImpl(BlogService.Descriptor, ServerReflection.Descriptor);

                server = new Server()
                {
                    Services =
                    {
                        BlogService.BindService(new BlogServiceImpl()),
                        ServerReflection.BindService(blogServiceReflectionServiceImpl),
                        GreetingService.BindService(new GreetingServiceImpl()),
                        //ServerReflection.BindService(greetingServiceReflectionServiceImpl),
                        CalculatorService.BindService(new CalculatorServiceImpl()),
                        //ServerReflection.BindService(calculatorServiceReflectionServiceImpl)
                    },
                    Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
                };
                server.Start();
                Console.WriteLine("The server is listening on the port :" + port);
                Console.ReadKey();
            }
            catch (IOException e)
            {
                Console.WriteLine("The server failed to start:" + e.Message);
                throw;
            }
            finally
            {
                if (server != null)
                {
                    server.ShutdownAsync().Wait();
                }
            }
        }
コード例 #12
0
        public void Init()
        {
            serviceImpl = new ReflectionServiceImpl(ServerReflection.Descriptor);

            server = new Server
            {
                Services = { ServerReflection.BindService(serviceImpl) },
                Ports    = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
            };
            server.Start();
            channel = new Channel(Host, server.Ports.Single().BoundPort, ChannelCredentials.Insecure);

            client = new ServerReflection.ServerReflectionClient(channel);
        }
コード例 #13
0
        static void Main(string[] args)
        {
            Server server = null;

            try
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(GreetingService.Descriptor, ServerReflection.Descriptor);

                var serverCert = File.ReadAllText("ssl/server.crt");
                var serverKey  = File.ReadAllText("ssl/server.key");
                var keypair    = new KeyCertificatePair(serverCert, serverKey);
                var cacert     = File.ReadAllText("ssl/ca.crt");

                var credentials = new SslServerCredentials(
                    new List <KeyCertificatePair>()
                {
                    keypair
                }, cacert, true);

                server = new Server()
                {
                    Services =
                    {
                        GreetingService.BindService(new GreetingServiceImp()),
                        CalculatorService.BindService(new CalculatorServiceImp()),
                        SqrtService.BindService(new SqrtServiceImpl()),
                        GreetDeadlinesService.BindService(new GreetingDeadlinesImpl()),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },

                    Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
                };

                server.Start();

                Console.WriteLine("The server is listening on the port {0}", Port);
                Console.ReadKey();
            }
            catch (IOException e)
            {
                Console.WriteLine("The server failed to start: ", e.Message);
            }
            finally
            {
                if (server != null)
                {
                    server.ShutdownAsync().Wait();
                }
            }
        }
コード例 #14
0
        public void Init()
        {
            serviceImpl = new ReflectionServiceImpl(ServerReflection.Descriptor);

            // Disable SO_REUSEPORT to prevent https://github.com/grpc/grpc/issues/10755
            server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) })
            {
                Services = { ServerReflection.BindService(serviceImpl) },
                Ports    = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } }
            };
            server.Start();
            channel = new Channel(Host, server.Ports.Single().BoundPort, ChannelCredentials.Insecure);

            client = new ServerReflection.ServerReflectionClient(channel);
        }
コード例 #15
0
        static void Main(string[] args)
        {
            //FOR SSL------------------------------------
            //var serverCert = File.ReadAllText("ssl/server.crt");
            //var serverKey = File.ReadAllText("ssl/server.key");
            //var keypair = new KeyCertificatePair(serverCert, serverKey);
            //var caCert = File.ReadAllText("ssl/ca.crt");

            //var credentials = new SslServerCredentials(new List<KeyCertificatePair>() { keypair }, caCert, true);
            //---------------------------------------------------
            //FOR REFLECTION
            var reflectionServiceImpl = new ReflectionServiceImpl(GreetingService.Descriptor, ServerReflection.Descriptor);
            //-------------------------------------------------------

            Server server = null;

            try
            {
                server = new Server()
                {
                    Services =
                    {
                        GreetingService.BindService(new GreetingServiceImpl()),
                        ServerReflection.BindService(reflectionServiceImpl) //FOR REFLECTION
                    },                                                      //it tells server when client calls greet function, it will call the implementaion of it which is GreetingServiceImpl()

                    Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }//WITHOUT SSL
                    //Ports = { new ServerPort("localhost", Port, credentials) }//WITH SSL
                };
                server.Start();
                Console.WriteLine("The Server is listening on Port : " + Port);
                Console.ReadKey();
            }
            catch (IOException ex)
            {
                Console.WriteLine("The Server failed to start : " + ex.Message);
                throw;
            }
            finally
            {
                if (server != null)
                {
                    server.ShutdownAsync().Wait();//running synchronously here.can be asyncronous if server and client is in different system
                }
            }
        }
コード例 #16
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)
        {
            services.AddLogging(configure => configure.AddConsole());
            services.AddSingleton <AppContainer>();

            services.AddSingleton(_ => new StorageOptions(Configuration["Storage"]));

            services.AddMediatR(typeof(Startup).Assembly);
            services.AddValidators(typeof(Startup));
            services.AddBehaviorsForRequest <IDriveRequest>(typeof(Startup));
            services.AddErrorHandling(typeof(Startup));

            services.AddControllers();
            services.AddHttpContextAccessor();

            services.AddHealthChecks()
            .AddCheck <LivenessCheck>("liveness", tags: new List <string> {
                "liveness"
            })
            .AddCheck <ReadinessCheck>("readiness", tags: new List <string> {
                "readiness"
            });

            services.AddSingleton(_ =>
                                  new ValuesContainer(Configuration["SecretValue"], Configuration["NotSecretValue"]));

            services.AddSingleton(sp =>
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(FileService.Descriptor, ServerReflection.Descriptor);
                var server = new Server
                {
                    Services =
                    {
                        FileService.BindService(new Grpc.FileService(sp.GetService <StorageOptions>())),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports = { new ServerPort("localhost", 3000, ServerCredentials.Insecure) },
                };
                return(server);
            });

            services.AddHostedService <GrpcHostedService>();
        }
コード例 #17
0
        static async Task Main(string[] args)
        {
            var reflectionServiceImpl = new ReflectionServiceImpl(
                BlogService.Descriptor
                , ServerReflection.Descriptor
                );

            var server = new Server
            {
                Services =
                {
                    BlogService.BindService(new BlogServiceImpl()),
                    ServerReflection.BindService(reflectionServiceImpl),
                },
                Ports =
                {
                    new ServerPort(Host, Port, ServerCredentials.Insecure)
                }
            };

            try
            {
                server.Start();
                Console.WriteLine("Server is listening.");
                Console.ReadLine();
            }
            catch (IOException ex)
            {
                Console.WriteLine($"IO Error: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
            finally
            {
                if (server != null)
                {
                    await server.ShutdownAsync();
                }
            }
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: umialpha/telepathy-poc
        public static void Main(string[] args)
        {
            var    reflectionServiceImpl = new ReflectionServiceImpl(Greeter.Descriptor, ServerReflection.Descriptor);
            Server server = new Server
            {
                Services =
                {
                    // the server will serve 2 services, the Greeter and the ServerReflection
                    Greeter.BindService(new GreeterImpl()),
                    ServerReflection.BindService(reflectionServiceImpl)
                },
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };

            server.Start();

            Console.WriteLine("Greeter server listening on port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
コード例 #19
0
        static void Main(string[] args)
        {
            var serverCert        = File.ReadAllText("../../../ssl/server.crt");
            var serverKey         = File.ReadAllText("../../../ssl/server.key");
            var caCert            = File.ReadAllText("../../../ssl/ca.crt");
            var channelCredential = new SslServerCredentials(new List <KeyCertificatePair> {
                new KeyCertificatePair(serverCert, serverKey)
            }, caCert, true);
            var serviceDesc = new ReflectionServiceImpl(GreetingService.Descriptor, ServerReflection.Descriptor);

            Grpc.Core.Server server = new Grpc.Core.Server
            {
                Services = { GreetingService.BindService(new GreetingServiceImpl()),
                             PrimeNumberDecomposition.BindService(new PrimeNumberDecompositionServiceImpl()),
                             SquareRootService.BindService(new SquareRootServiceImpl()),
                             ServerReflection.BindService(serviceDesc) },
                //Ports = { new ServerPort("localhost", 5000, ServerCredentials.Insecure) }
                Ports = { new ServerPort("localhost", 5000, channelCredential) }
            };
            server.Start();
            Console.WriteLine("server started...");
            Console.ReadLine();
        }
コード例 #20
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <HealthService>()
            .As <IHealthService>()
            .SingleInstance();

            builder.RegisterType <StartupManager>()
            .As <IStartupManager>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.ConstraintsGroups))
            .SingleInstance();

            builder.RegisterType <ShutdownManager>()
            .As <IShutdownManager>()
            .SingleInstance();

            builder.RegisterType <RiskConstrainsInitializer>()
            .AsSelf()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.ConstraintsGroups));

            builder.RegisterType <OperationValidationRepository>()
            .As <IOperationValidationRepository>()
            .WithParameter(TypedParameter.From(_settings.ConnectionString(x => x.Db.AzureDataConnString)))
            .SingleInstance();

            builder.RegisterType <StatisticsRepository>()
            .As <IStatisticsRepository>()
            .AsSelf()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.Db.MongoDataConnString))
            .SingleInstance();

            builder.RegisterType <OperationValidationService>()
            .As <IOperationValidationService>()
            .SingleInstance();

            builder.RegisterType <StatisticsService>()
            .As <IStatisticsService>()
            .SingleInstance();

            builder.RegisterType <OperationRiskEstimator>()
            .As <IOperationRiskEstimator>()
            .SingleInstance();

            builder.RegisterType <RiskConstraintsRegistry>()
            .As <IRiskConstraintsRegistry>()
            .SingleInstance();

            builder.RegisterType <RiskConstraintsRegistryConfigurator>()
            .As <IRiskConstraintsRegistryConfigurator>()
            .SingleInstance();

            builder.RegisterType <RiskConstraintsFactory>()
            .As <IRiskConstraintsFactory>()
            .SingleInstance();

            builder.RegisterType <BlockchainRiskControlServiceImpl>()
            .AsSelf()
            .SingleInstance();

            builder.Register(ctx =>
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(
                    BlockchainRiskControlService.Descriptor
                    );
                return(new Server
                {
                    Services =
                    {
                        BlockchainRiskControlService.BindService(ctx.Resolve <BlockchainRiskControlServiceImpl>()),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports =
                    {
                        new ServerPort("0.0.0.0", 5005, ServerCredentials.Insecure)
                    }
                });
            }
                             ).SingleInstance();

            builder.RegisterInstance(
                new TelegramBotClient(string.IsNullOrEmpty(_settings.CurrentValue.Telegram?.Token) ? "1234:test" : _settings.CurrentValue.Telegram?.Token)
                ).As <ITelegramBotClient>().SingleInstance();
        }
コード例 #21
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <StartupManager>()
            .As <IStartupManager>()
            .AutoActivate()
            .SingleInstance();

            builder.RegisterType <ShutdownManager>()
            .As <IShutdownManager>()
            .AutoActivate()
            .SingleInstance();

            builder.Register(ctx =>
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(
                    MarketDataService.Descriptor
                    );
                return(new Server
                {
                    Services =
                    {
                        MarketDataService.BindService(
                            new MarketDataServiceClient(ctx.Resolve <RedisService>())),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports =
                    {
                        new ServerPort("0.0.0.0", _appSettings.CurrentValue.MarketDataService.GrpcPort,
                                       ServerCredentials.Insecure)
                    }
                });
            }
                             ).SingleInstance();

            builder.Register(c =>
            {
                var lazy = new Lazy <ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(_appSettings.CurrentValue.MarketDataService.Redis.Configuration));
                return(lazy.Value);
            })
            .As <IConnectionMultiplexer>()
            .SingleInstance();

            builder.Register(c => c.Resolve <IConnectionMultiplexer>().GetDatabase())
            .As <IDatabase>();

            builder.RegisterMarketProfileClient(_appSettings.CurrentValue.MarketDataService.MarketProfileUrl);

            builder.RegisterInstance(
                new Candleshistoryservice(new Uri(_appSettings.CurrentValue.MarketDataService.CandlesHistoryUrl))
                ).As <ICandleshistoryservice>().SingleInstance();

            builder.RegisterType <InitService>()
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.MarketDataService.MarketDataInterval))
            .AsSelf()
            .SingleInstance();

            builder.RegisterType <QuotesFeedSubscriber>()
            .WithParameter(new NamedParameter("connectionString", _appSettings.CurrentValue.MarketDataService.RabbitMq.QuotesConnectionString))
            .WithParameter(new NamedParameter("exchangeName", _appSettings.CurrentValue.MarketDataService.RabbitMq.QuotesExchangeName))
            .AsSelf()
            .SingleInstance();

            builder.RegisterType <LimitOrdersSubscriber>()
            .WithParameter(new NamedParameter("connectionString", _appSettings.CurrentValue.MarketDataService.RabbitMq.LimitOrdersConnectionString))
            .WithParameter(new NamedParameter("exchangeName", _appSettings.CurrentValue.MarketDataService.RabbitMq.LimitOrdersExchangeName))
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.MarketDataService.MarketDataInterval))
            .AsSelf()
            .SingleInstance();

            builder.RegisterAssetsClient(_appSettings.CurrentValue.AssetsServiceClient);

            builder.RegisterType <RedisService>()
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.MarketDataService.MarketDataInterval))
            .SingleInstance();

            builder.RegisterType <CleanupHandler>()
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.MarketDataService.MarketDataInterval))
            .As <IStartable>()
            .AutoActivate()
            .SingleInstance();

            builder.Register(ctx =>
            {
                return(_appSettings.CurrentValue.MarketDataService.MyNoSqlServer.Enabled
                    ? new MyNoSqlServer.DataWriter.MyNoSqlServerDataWriter <Ticker>(() =>
                                                                                    _appSettings.CurrentValue.MarketDataService.MyNoSqlServer.ServiceUrl,
                                                                                    _appSettings.CurrentValue.MarketDataService.MyNoSqlServer.TickersTableName)
                    : (IMyNoSqlServerDataWriter <Ticker>) new MockNoSqlServerDataWriter <Ticker>());
            }).As <IMyNoSqlServerDataWriter <Ticker> >().SingleInstance();

            builder.Register(ctx =>
            {
                return(_appSettings.CurrentValue.MarketDataService.MyNoSqlServer.Enabled
                    ? new MyNoSqlServer.DataWriter.MyNoSqlServerDataWriter <Price>(() =>
                                                                                   _appSettings.CurrentValue.MarketDataService.MyNoSqlServer.ServiceUrl,
                                                                                   _appSettings.CurrentValue.MarketDataService.MyNoSqlServer.PricesTableName)
                    : (IMyNoSqlServerDataWriter <Price>) new MockNoSqlServerDataWriter <Price>());
            }).As <IMyNoSqlServerDataWriter <Price> >().SingleInstance();
        }
コード例 #22
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <StartupManager>()
            .As <IStartupManager>()
            .AutoActivate()
            .SingleInstance();

            builder.RegisterType <ShutdownManager>()
            .As <IShutdownManager>()
            .AutoActivate()
            .SingleInstance();

            builder.RegisterType <Link4PayServiceImpl>()
            .AsSelf()
            .WithParameter("supportedCountries", _appSettings.CurrentValue.Link4PayService.SupportedCountries)
            .WithParameter("supportedCurrencies", _appSettings.CurrentValue.Link4PayService.SupportedCurrencies)
            .SingleInstance();

            builder.Register(ctx =>
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(
                    Link4PayService.Descriptor
                    );
                return(new Server
                {
                    Services =
                    {
                        Link4PayService.BindService(ctx.Resolve <Link4PayServiceImpl>()),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports =
                    {
                        new ServerPort("0.0.0.0", _appSettings.CurrentValue.Link4PayService.GrpcPort,
                                       ServerCredentials.Insecure)
                    }
                });
            }
                             ).SingleInstance();

            builder.RegisterInstance(
                new KeyVaultClient(
                    async(string authority, string resource, string scope) =>
            {
                var authContext = new AuthenticationContext(authority);
                var clientCred  =
                    new ClientCredential(_appSettings.CurrentValue.Link4PayService.KeyVault.ClientId, _appSettings.CurrentValue.Link4PayService.KeyVault.ClientSecret);
                var result = await authContext.AcquireTokenAsync(resource, clientCred);
                if (result == null)
                {
                    throw new InvalidOperationException("Failed to retrieve access token for Key Vault");
                }

                return(result.AccessToken);
            }
                    ));

            builder.RegisterInstance(_appSettings.CurrentValue.Link4PayService.Link4Pay);
            builder.RegisterInstance(_appSettings.CurrentValue.Link4PayService.KeyVault);

            builder.RegisterType <EncryptionService>()
            .As <IEncryptionService>()
            .SingleInstance();

            builder.RegisterType <Link4PayApiService>()
            .As <ILink4PayApiService>()
            .SingleInstance();

            builder.RegisterType <AntiFraudChecker>()
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.Link4PayService.AntiFraudCheckPaymentPeriod))
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.Link4PayService.AntiFraudCheckRegistrationDateSince))
            .WithParameter("notificationEmail", _appSettings.CurrentValue.Link4PayService.AntiFraudNotificationEmail)
            .WithParameter("chatId", _appSettings.CurrentValue.Link4PayService.Telegram.ChatId);

            builder.RegisterType <PaymentOkEmailSender>()
            .As <IPaymentNotifier>()
            .SingleInstance();

            builder.RegisterInstance(_appSettings.CurrentValue.Link4PayService.Telegram);

            builder.RegisterInstance(
                string.IsNullOrEmpty(_appSettings.CurrentValue.Link4PayService.Telegram.Token)
                ? new Mock <ITelegramBotClient>().Object
                : new TelegramBotClient(_appSettings.CurrentValue.Link4PayService.Telegram.Token)
                ).As <ITelegramBotClient>().SingleInstance();
        }
コード例 #23
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)
        {
            // AutoMapper provides this extension method, which accepts 1-N references to an assembly. AutoMapper then
            // uses reflection to scan the assemblies for any classes that extend `Profile`. All we need to do
            // is tell AutoMapper which assemblies contain profiles and it will wire everything else up for us.
            services.AddAutoMapper(Assembly.GetExecutingAssembly());

            // This will add the our gRPC interceptors to all gRPC services. Interceptors
            // are similar to http middleware (in fact, they're implemented with some of the same code
            // in C#), but are used in a slightly different way since they act on the gRPC layer, not the HTTP layer.
            services.AddGrpc(options =>
            {
                options.EnableDetailedErrors = true;

                // This interceptor logs the request headers of incoming requests.
                options.Interceptors.Add <RequestLoggingGrpcServerInterceptor>();
            });

            // Instantiate a singleton instance of the Grpc health check service. The gRPC health check service is an
            // optional service that gRPC servers can run which report on the health of the server. If your application has
            // the ability and need to report when it's in an unhealthy but still running state, you can implement overrides
            // for the health service endpoints to report the status as needed. By default, the service will be set to Serving,
            // and as long as your service is available no other work needs to be done for that status to continue to be reported.
            //
            // Note that unlike other services, this service is registered as an object *instance* rather than a type.
            // The result is that the provided object will be used as the singleton for all dependents of the type of the object.
            // This pattern is required at times but should only be used when necessary.
            var healthService = new HealthServiceImpl();

            healthService.SetStatus("", HealthCheckResponse.Types.ServingStatus.Serving);
            services.AddSingleton(healthService);

            // The reflection service acts as a reporting endpoint which will use reflection to identify all gRPC services that
            // are running on this server and provide a gRPC service that can report on this information. This can be very helpful
            // as it allows various gRPC tools to act as clients and learn about what services are available.
            // Tools such as BloomRPC can also make use of this information to provide skeleton requests, making the service easier to consume.
            var reflectionServiceImpl = new ReflectionServiceImpl(
                new List <Google.Protobuf.Reflection.ServiceDescriptor>
            {
                Health.Descriptor
            }
                );

            services.AddSingleton(reflectionServiceImpl);

            // This extension method registers the feature management systems classes with the service provider, including
            // `IFeatureManager` which application code can depend on to provide information about what features are enabled.
            services.AddFeatureManagement(Configuration);

            services.AddOptions <V2RepositorySettings>()
            .Bind(Configuration.GetSection("V2RepositorySettings"))
            .ValidateDataAnnotations();

            // Here, we make use of the feature management system to determine which repository implementation should be used
            // at runtime. We register a singleton of each repository (since they hold data in memory as a mock "database"),
            // then map their shared interface to a delegate which extracts the feature manager from the provider to determine
            // which concrete type the interface should map to for the given request. By making the interface scoped, we
            // ensure that if the feature flag ever changes, the repository will be recreated with the new backing implementation
            // for each request.
            services.AddScoped <WeatherForecastRepository>();
            services.AddScoped <WeatherForecastRepositoryV2>();
            services.AddScoped <IWeatherForecastRepository>(provider =>
            {
                var featureManager = provider.GetRequiredService <IFeatureManager>();

                // Normally you should avoid calling `.Result` on a Task<T> object, but we have no choice here as the delegate
                // we're using to make use of the feature flag is not asynchronous. Thankfully, this blocking call will only occur
                // once at startup.
                if (featureManager.IsEnabledAsync(nameof(FeatureFlags.UseExperimentalRepository)).Result)
                {
                    return(provider.GetRequiredService <WeatherForecastRepositoryV2>());
                }

                return(provider.GetRequiredService <WeatherForecastRepository>());
            });

            // The feature management system also allows applications to implement the `IDisabledFeaturesHandler` to register
            // for notifications when callers attempt to access a feature that is blocked.
            services.AddSingleton <IDisabledFeaturesHandler, DisabledFeatureLoggingHandler>();
        }
コード例 #24
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await Task.Factory.StartNew(() =>
            {
                foreach (var serviceGroup in StatefulServices.GroupBy(x => x.Value))
                {
                    switch (serviceGroup.Key)
                    {
                    case EventSourcedStatefulService _:
                        Server.Services.Add(
                            Cloudstate.Eventsourced.EventSourced.BindService(new EntityCollectionService(
                                                                                 LoggerFactory,
                                                                                 Config,
                                                                                 serviceGroup.ToDictionary(
                                                                                     x => x.Key,
                                                                                     x => x.Value as IEventSourcedStatefulService
                                                                                     ),
                                                                                 new Context(new ResolvedServiceCallFactory(StatefulServices))
                                                                                 ))
                            );
                        break;

                    case CrdtStatefulService _:
                        Server.Services.Add(
                            Cloudstate.Crdt.Crdt.BindService(new CrdtEntityCollectionService(
                                                                 LoggerFactory,
                                                                 serviceGroup.ToDictionary(
                                                                     x => x.Key,
                                                                     x => x.Value as ICrdtStatefulService
                                                                     ),
                                                                 new Context(new ResolvedServiceCallFactory(StatefulServices))
                                                                 ))
                            );
                        break;

                    default:
                        throw new NotImplementedException($"Unknown stateful service implementation of {serviceGroup.Key}");
                    }
                }

                Server.Services.Add(
                    EntityDiscovery.BindService(
                        new EntityDiscoveryService(
                            LoggerFactory,
                            StatefulServices
                            )
                        )
                    );

                // TODO: Feature flag this.
                var reflectionServiceImpl = new ReflectionServiceImpl(
                    StatefulServices.Values.Select(x => x.ServiceDescriptor)
                    );
                Server.Services.Add(
                    ServerReflection.BindService(
                        reflectionServiceImpl
                        )
                    );

                Server.Start();
                Logger.LogInformation(
                    $"Server listening on [{Config.Host}:{Config.Port}]"
                    );
            }, cancellationToken);
        }