/// <summary> /// Initializes a new instance of the <see cref="IHostBuilder"/> class with pre-configured defaults. /// </summary> /// <param name="useSimpleConsoleLogger"></param> /// <param name="minSimpleConsoleLoggerLogLevel"></param> /// <param name="resolvers"></param> /// <returns>The initialized <see cref="IHostBuilder"/>.</returns> public static IHostBuilder CreateDefaultBuilder( bool useSimpleConsoleLogger, LogLevel minSimpleConsoleLoggerLogLevel, params Type[] resolvers) { var builder = MagicOnionHost.CreateDefaultBuilder(); builder.UseWindowsService(); ConfigureHostConfigurationDefault(builder); ConfigureServiceProvider(builder); ConfigureLoggingDefault(builder, useSimpleConsoleLogger, minSimpleConsoleLoggerLogLevel); var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.SetBasePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); configurationBuilder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); configurationBuilder.AddEnvironmentVariables(); var configuration = configurationBuilder.Build(); builder.UseMagicOnion( new List <ServerPort> { new ServerPort(IPAddress.Any.ToString(), !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GCD_NODE_LISTENING_PORT")) ? (int.TryParse(Environment.GetEnvironmentVariable("GCD_NODE_LISTENING_PORT"), out var port) ? port : configuration.GetValue <int>("GCD_NODE_LISTENING_PORT")) : configuration.GetValue <int>("GCD_NODE_LISTENING_PORT"), ServerCredentials.Insecure) },
public static async Task Main(string[] args) { var magicOnionHost = MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion(new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true), new ServerPort("0.0.0.0", 12345, ServerCredentials.Insecure)) .UseConsoleLifetime() .Build(); var webHost = Host.CreateDefaultBuilder(args) .ConfigureServices(collection => { collection.AddSingleton <MagicOnionServiceDefinition>(magicOnionHost.Services.GetService <MagicOnionHostedServiceDefinition>().ServiceDefinition); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureKestrel(serverOptions => serverOptions.AllowSynchronousIO = true) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddConsole(); }) .UseUrls("http://0.0.0.0:5432") .UseStartup <Startup>(); }) .Build(); await Task.WhenAll(webHost.RunAsync(), magicOnionHost.RunAsync()); }
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(); } }
private static async Task Main(string[] args) { //un services var magicOnionHost = MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion( new MagicOnionOptions(true), new ServerPort("127.0.0.1", 12345, ServerCredentials.Insecure) ) .UseConsoleLifetime() .Build(); // NuGet: Microsoft.AspNetCore.Server.Kestrel var webHost = new WebHostBuilder() .ConfigureServices( collection => { collection.AddSingleton( magicOnionHost.Services.GetService <MagicOnionHostedServiceDefinition>().ServiceDefinition ); // add the following codes collection.Configure <KestrelServerOptions>(options => { options.AllowSynchronousIO = true; }); } ) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>() .UseUrls("http://0.0.0.0:9999") .Build(); //webHost.Run(); // Run and wait both. await Task.WhenAll(webHost.RunAsync(), magicOnionHost.RunAsync()); }
static async Task Main(string[] args) { await MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion( new ServerPort("localhost", 20201, ServerCredentials.Insecure) ) .RunConsoleAsync(); }
static async Task Main(string[] args) { //GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger()); await MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion() .RunConsoleAsync(); }
static async Task Main(string[] args) { GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger()); await MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion( new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true), new ServerPort("localhost", 12345, ServerCredentials.Insecure)) .RunConsoleAsync(); }
static async Task Main(string[] args) { GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger()); await MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion(new[] { new ServerPort("0.0.0.0", 12345, ServerCredentials.Insecure) }) .RunConsoleAsync(); }
static async Task Main(string[] args) { //GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger()); await MagicOnionHost.CreateDefaultBuilder() .ConfigureLogging((context, logging) => { logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Trace); logging.AddZLoggerConsole(); }) .UseMagicOnion() .RunConsoleAsync(); }
static async Task Main(string[] args) { GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger()); // setup MagicOnion hosting. var magicOnionHost = MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion( new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true), new ServerPort(serverAddress, serverPort, ServerCredentials.Insecure)) .UseConsoleLifetime() .Build(); await magicOnionHost.RunAsync(); }
private static async Task Main(string[] args) { GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger()); await MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion( new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true), new ServerPort("0.0.0.0", 12345, ServerCredentials.Insecure)) .ConfigureServices((hostContext, services) => { services.AddSingleton <ConcurrentDictionary <string, ARWorldApplication> >(); }) .RunConsoleAsync(); }
static async Task Main(string[] args) { //GrpcEnvironment.SetLogger(new ConsoleLogger()); var isDevelopment = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") == "Development"; var creds = isDevelopment ? ChannelCredentials.Insecure : new SslCredentials(File.ReadAllText("./server.crt")); var clientMyService = MagicOnionClient.Create <IMyService>(new Channel("localhost", 12345, creds)); var hostTask = MagicOnionHost.CreateDefaultBuilder() //.UseMagicOnion() .UseMagicOnion(types: new [] { typeof(MyService), typeof(MyHub) }) .UseMagicOnion(configurationName: "MagicOnion-Management", types: new[] { typeof(ManagementService) }) .ConfigureServices((hostContext, services) => { services.Configure <MagicOnionHostingOptions>(options => { if (hostContext.HostingEnvironment.IsDevelopment()) { options.Service.GlobalStreamingHubFilters.Add <MyStreamingHubFilterAttribute>(); // options.Service.GlobalStreamingHubFilters.Add(new MyStreamingHubFilterAttribute(logger)); options.Service.GlobalFilters.Add <MyFilterAttribute>(); options.Service.GlobalFilters.Add <MyFilter2Attribute>(); options.Service.GlobalFilters.Add <MyFilter3Attribute>(); // options.Service.GlobalFilters.Add(new MyFilterAttribute(logger)); // options.ServerPorts = new[]{ new MagicOnionHostingServerPortOptions(){ Port = opti } options.ChannelOptions.MaxReceiveMessageLength = 1024 * 1024 * 10; options.ChannelOptions.Add(new ChannelOption("grpc.keepalive_time_ms", 10000)); }); services.Configure <MagicOnionHostingOptions>("MagicOnion-Management", options => { }); }) .RunConsoleAsync(); //var clientMyService = MagicOnionClient.Create<IMyService>(new Channel("localhost", 12345, creds)); var clientManagementService = MagicOnionClient.Create <IManagementService>(new Channel("localhost", 23456, creds)); var result = await clientMyService.HelloAsync(); var result2 = await clientManagementService.FooBarAsync(); var clientHub = StreamingHubClient.Connect <IMyHub, IMyHubReceiver>(new Channel("localhost", 12345, creds), null); var result3 = await clientHub.HelloAsync(); await hostTask; }
static async Task Main(string[] args) { await MagicOnionHost.CreateDefaultBuilder() .ConfigureServices((hostContext, services) => { services.AddMagicOnionJwtAuthentication <CustomJwtAuthenticationProvider>(options => { var preSharedKey = Convert.FromBase64String(hostContext.Configuration.GetSection("JwtAuthApp.Server:Secret").Value); var algorithm = new HS512Algorithm(preSharedKey); // Use Symmetric algorithm (HMAC SHA-512) options.Encoder = new JwtEncoder(algorithm); options.Decoder = new JwtDecoder(new JwtAlgorithmResolver(algorithm)); options.Expire = TimeSpan.FromSeconds(5); }); }) .UseMagicOnion() .RunConsoleAsync(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var magicOnionHost = MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion( new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true), new ServerPort("127.0.0.1", 19021, ServerCredentials.Insecure)) .UseConsoleLifetime() .Build(); services.AddSingleton <MagicOnionServiceDefinition>(magicOnionHost.Services.GetService <MagicOnionHostedServiceDefinition>().ServiceDefinition); magicOnionHost.StartAsync(); services.AddMvc(e => e.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddControllers(); services.AddCors(ops => ops.AddPolicy("cors", policy => policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); //return services.AddAbp<AbpGrpcServiceDemoModule>(); }
static async Task Main(string[] args) { GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger()); // for SSL/TLS connection //var config = new ConfigurationBuilder().AddEnvironmentVariables().Build(); //var certificates = new List<KeyCertificatePair> { new KeyCertificatePair(File.ReadAllText("server.crt"), File.ReadAllText("server.key")) }; //var credential = new SslServerCredentials(certificates); await MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion( new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true), new ServerPort("localhost", 12345, ServerCredentials.Insecure)) // for SSL/TLS Connection //new ServerPort(config.GetValue<string>("MAGICONION_HOST", "127.0.0.1"), 12345, credential)) .RunConsoleAsync(); }
static async Task Main(string[] args) { GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger()); List <ChannelOption> options = new List <ChannelOption> { new ChannelOption("grpc.keepalive_time_ms", 2000), new ChannelOption("grpc.keepalive_timeout_ms", 3000), new ChannelOption("grpc.http2.min_time_between_pings_ms", 5000), }; await MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion( new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true), new ServerPort("0.0.0.0", 12345, ServerCredentials.Insecure), options ) .RunConsoleAsync(); }
/// <summary> /// Initializes a new instance of the <see cref="IHostBuilder"/> class with pre-configured defaults. /// </summary> /// <param name="configureListeningPort">Listening port</param> /// <param name="loggerBuilder">Logger builder</param> /// <param name="resolvers">Resolvers</param> /// <returns>The initialized <see cref="IHostBuilder"/>.</returns> public static IHostBuilder CreateDefaultBuilder( Func <IConfiguration, int> configureListeningPort, Func <ILoggerBuilder, IConfiguration, ILoggerBuilder> loggerBuilder, params Type[] resolvers) { var builder = MagicOnionHost.CreateDefaultBuilder(); ConfigureAppConfigurationDefault(builder); ConfigureServices(builder); ConfigureLoggingDefault(builder, loggerBuilder); var configurationBuilder = new ConfigurationBuilder(); SetConfigurationBuilder(configurationBuilder); var configuration = configurationBuilder.Build(); builder.UseMagicOnion( new List <ServerPort> { new ServerPort(IPAddress.Any.ToString(), configureListeningPort(configuration), ServerCredentials.Insecure) }, new MagicOnionOptions(true) { MagicOnionLogger = new MagicOnionLogToGrpcLogger() }, types: resolvers.Select(resolver => { var targetType = typeof(IResolver); if (!targetType.GetTypeInfo().IsAssignableFrom(resolver.GetTypeInfo())) { throw new ArgumentException(nameof(resolver), $"Type {resolver.Name} should implement IResolver interface."); } return(resolver); }).Concat(new[] { typeof(Hubs.Hub.NodeHub) })); return(builder); }
public static async Task Run(DelegateLogger dLogger) { //GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger()); GrpcEnvironment.SetLogger(new CompositeLogger( new DebugConsoleLogger(), dLogger)); tokenSource = new CancellationTokenSource(); using var ihost = await MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion( new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true), new ServerPort("0.0.0.0", 12345, ServerCredentials.Insecure)) //.UseConsoleLifetime() .StartAsync(tokenSource.Token); host = ihost; await ihost.WaitForShutdownAsync(); }
static async Task Main(string[] args) { //GrpcEnvironment.SetLogger(new Grpc.Core.Logging.ConsoleLogger()); await MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion() .ConfigureServices((hostContext, services) => { services.AddMagicOnionOpenTelemetry((options, meterOptions) => { // open-telemetry with Prometheus exporter meterOptions.MetricExporter = new PrometheusExporter(new PrometheusExporterOptions() { Url = options.MetricsExporterEndpoint }); }, (options, provider, tracerBuilder) => { // open-telemetry with Zipkin exporter tracerBuilder.UseZipkinExporter(o => { o.ServiceName = "ChatApp.Server"; o.Endpoint = new Uri(options.TracerExporterEndpoint); }); // ConsoleExporter will show current tracer activity tracerBuilder.UseConsoleExporter(); }); services.AddHostedService <PrometheusExporterMetricsService>(); }) .ConfigureServices((hostContext, services) => { var meterProvider = services.BuildServiceProvider().GetService <MeterProvider>(); services.Configure <MagicOnionHostingOptions>(options => { options.Service.GlobalFilters.Add(new OpenTelemetryCollectorFilterAttribute()); options.Service.GlobalStreamingHubFilters.Add(new OpenTelemetryHubCollectorFilterAttribute()); options.Service.MagicOnionLogger = new OpenTelemetryCollectorLogger(meterProvider); }); }) .RunConsoleAsync(); }
private static async Task Main(string[] args) { // Main gRPC Host var magicOnionHost = MagicOnionHost.CreateDefaultBuilder() .UseMagicOnion() .ConfigureServices((context, collection) => { // afe }) .Build(); var swaggerWeb = new WebHostBuilder() .ConfigureServices(collection => { // Add MagicOnionServiceDefinition for reference from Startup. collection.AddSingleton(magicOnionHost.Services.GetService <MagicOnionHostedServiceDefinition>() .ServiceDefinition); }) .UseKestrel() .Build(); await Task.WhenAll(magicOnionHost.RunAsync(), swaggerWeb.RunAsync()); }
static async Task Main(string[] args) { // ServiceLocatorHelper.CreateService<UnaryService, ICalcSerivce>(null); const string GrpcHost = "localhost"; Console.WriteLine("Server:::"); //Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG"); //Environment.SetEnvironmentVariable("GRPC_TRACE", "all"); Environment.SetEnvironmentVariable("SETTINGS_MAX_HEADER_LIST_SIZE", "1000000"); GrpcEnvironment.SetLogger(new ConsoleLogger()); var options = new MagicOnionOptions(true) { //MagicOnionLogger = new MagicOnionLogToGrpcLogger(), MagicOnionLogger = new MagicOnionLogToGrpcLoggerWithNamedDataDump(), GlobalFilters = new MagicOnionFilterAttribute[] { }, EnableCurrentContext = true, DisableEmbeddedService = true, }; var magicOnionHost = MagicOnionHost.CreateDefaultBuilder(useSimpleConsoleLogger: true) .UseMagicOnion(options, new ServerPort("localhost", 12345, ServerCredentials.Insecure)) .UseConsoleLifetime() .Build(); // test webhost // NuGet: Microsoft.AspNetCore.Server.Kestrel var webHost = new WebHostBuilder() .ConfigureServices(collection => { // Add MagicOnionServiceDefinition for reference from Startup. collection.AddSingleton <MagicOnionServiceDefinition>(magicOnionHost.Services.GetService <MagicOnionServiceDefinition>()); }) .UseKestrel() .UseStartup <Startup>() .UseUrls("http://localhost:5432") .Build(); await Task.WhenAll(webHost.RunAsync(), magicOnionHost.RunAsync()); //webHost.Run(); //Console.ReadLine(); //{ // var channel = new Channel("localhost:12345", ChannelCredentials.Insecure); // var client = StreamingHubClient.Connect<IChatHub, IMessageReceiver2>(channel, new Receiver()); // Console.WriteLine("Call to Server"); // await client.JoinAsync("me", "foo"); // await Task.WhenAll( // client.SendMessageAsync("a"), // client.SendMessageAsync("b"), // client.SendMessageAsync("c"), // client.SendMessageAsync("d"), // client.SendMessageAsync("e")); // Console.WriteLine("OK to Send"); // await client.DisposeAsync(); // await channel.ShutdownAsync(); //} }
static async Task Main(string[] args) { //添加 json 文件路径 var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); //创建配置根对象 var Configuration = builder.Build(); //Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG"); //Environment.SetEnvironmentVariable("GRPC_TRACE", "all"); Environment.SetEnvironmentVariable("SETTINGS_MAX_HEADER_LIST_SIZE", "1000000"); GrpcEnvironment.SetLogger(new ConsoleLogger()); var options = new MagicOnionOptions(true) { MagicOnionLogger = new MagicOnionLogToGrpcLoggerWithNamedDataDump(), GlobalFilters = new MagicOnionFilterAttribute[] { }, EnableCurrentContext = true, DefaultGroupRepositoryFactory = new ConcurrentDictionaryGroupRepositoryFactory(), DisableEmbeddedService = true, }; var conn = ConnectionMultiplexer.Connect(Configuration["RedisConn"]); options.ServiceLocator.Register(conn); options.ServiceLocator.Register(MessagePackSerializer.DefaultResolver); options.ServiceLocator.Register <IMagicOnionLogger>(new NullMagicOnionLogger()); //IServiceCollection services = new ServiceCollection(); //services.AddTransient<ISomeService>(sp => new FooService(5)); //services.AddAutoMapper(typeof(Source)); //var provider = services.BuildServiceProvider(); //using (var scope = provider.CreateScope()) //{ // var mapper = scope.ServiceProvider.GetService<IMapper>(); // foreach (var typeMap in mapper.ConfigurationProvider.GetAllTypeMaps()) // { // Console.WriteLine($"{typeMap.SourceType.Name} -> {typeMap.DestinationType.Name}"); // } // foreach (var service in services) // { // Console.WriteLine(service.ServiceType + " - " + service.ImplementationType); // } // var dest = mapper.Map<Dest2>(new Source2()); // Console.WriteLine(dest.ResolvedValue); //} var magicOnionHost = MagicOnionHost.CreateDefaultBuilder(useSimpleConsoleLogger: true) .ConfigureServices((ctx, services) => { services.Configure <MongoAppSetting>(x => { x.MongoConn = Configuration["MongoConn"].ToString(); x.MongoDbDatabase = Configuration["MongoDbDatabase"].ToString(); }); services.AddAutoMapper((collect, cfg) => { cfg.AddProfile <MappingProfile>(); }, AppDomain.CurrentDomain.GetAssemblies()); services.Add(new ServiceDescriptor(typeof(IMapper), sp => new Mapper(sp.GetRequiredService <AutoMapper.IConfigurationProvider>(), sp.GetService), ServiceLifetime.Transient)); services.AddSingleton <MongoDbContext>(); services.AddScoped <IUserRepository, UserRepository>(); }) .UseMagicOnion(options, new ServerPort(Configuration["GrpcService:IP"], Convert.ToInt32(Configuration["GrpcService:Port"]), ServerCredentials.Insecure)) .UseConsoleLifetime() .Build(); var webHost = new WebHostBuilder() .ConfigureServices(collection => { // Add MagicOnionServiceDefinition for reference from Startup. collection.AddSingleton <MagicOnionServiceDefinition>(magicOnionHost.Services .GetService <MagicOnionServiceDefinition>()); }) .UseKestrel() .UseStartup <Startup>() .UseUrls("http://localhost:5432") .Build(); await Task.WhenAll(webHost.RunAsync(), magicOnionHost.RunAsync()); }