Microsoft.Extensions.Hosting pacakge, asp.net .
asp.net, API HostBuilder, gRPC- . - , (, Control-C):
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
public class Program
{
public static async Task Main(string[] args)
{
var hostBuilder = new HostBuilder();
....
await hostBuilder.RunConsoleAsync();
}
}
gRPC, / Grpc.Core.Server . - - , , , , , . IHostedService. , GrpcHostedService :
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Microsoft.Extensions.Hosting;
namespace Grpc.Host
{
public class GrpcHostedService: IHostedService
{
private Server _server;
public GrpcHostedService(Server server)
{
_server = server;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_server.Start();
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken) => await _server.ShutdownAsync();
}
}
. GrpcHostedService, , StartAsync , . , StopAsync, , Grpc.
Program.cs :
public class Program
{
public static async Task Main(string[] args)
{
var hostBuilder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
Server server = new Server
{
Services = {Greeter.BindService(new GreeterImpl())},
Ports = {new ServerPort("localhost", 5000, ServerCredentials.Insecure)}
};
services.AddSingleton<Server>(server);
services.AddSingleton<IHostedService, GrpcHostedService>();
});
await hostBuilder.RunConsoleAsync();
}
}
, StartAsync , , , StartAsync Server, , gRPC.
Control-C, StopAsync , StopAsync Server, .
HostBuilder .