Događaj
Power BI DataViz Svetsko prvenstvo
14. feb 16 - 31. mar 16
Sa 4 šanse za ulazak, možete osvojiti konferencijski paket i stići do LIVE Grand Finale u Las Vegasu
Saznajte višeOvaj pregledač više nije podržan.
Nadogradite na Microsoft Edge biste iskoristili najnovije funkcije, bezbednosne ispravke i tehničku podršku.
Napomena
This isn't the latest version of this article. For the current release, see the .NET 9 version of this article.
Upozorenje
This version of ASP.NET Core is no longer supported. For more information, see the .NET and .NET Core Support Policy. For the current release, see the .NET 9 version of this article.
Važno
This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
For the current release, see the .NET 9 version of this article.
gRPC integration with HttpClientFactory
offers a centralized way to create gRPC clients. It can be used as an alternative to configuring stand-alone gRPC client instances. Factory integration is available in the Grpc.Net.ClientFactory NuGet package.
The factory offers the following benefits:
HttpClientMessageHandler
.To register a gRPC client, the generic AddGrpcClient
extension method can be used within an instance of WebApplicationBuilder at the app's entry point in Program.cs
, specifying the gRPC typed client class and service address:
builder.Services.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
});
The gRPC client type is registered as transient with dependency injection (DI). The client can now be injected and consumed directly in types created by DI. ASP.NET Core MVC controllers, SignalR hubs and gRPC services are places where gRPC clients can automatically be injected:
public class AggregatorService : Aggregator.AggregatorBase
{
private readonly Greeter.GreeterClient _client;
public AggregatorService(Greeter.GreeterClient client)
{
_client = client;
}
public override async Task SayHellos(HelloRequest request,
IServerStreamWriter<HelloReply> responseStream, ServerCallContext context)
{
// Forward the call on to the greeter service
using (var call = _client.SayHellos(request))
{
await foreach (var response in call.ResponseStream.ReadAllAsync())
{
await responseStream.WriteAsync(response);
}
}
}
}
HttpClientFactory
creates the HttpMessageHandler
used by the gRPC client. Standard HttpClientFactory
methods can be used to add outgoing request middleware or to configure the underlying HttpClientHandler
of the HttpClient
:
builder.Services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.ConfigurePrimaryHttpMessageHandler(() =>
{
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(LoadCertificate());
return handler;
});
For more information, see Make HTTP requests using IHttpClientFactory.
gRPC interceptors can be added to clients using the AddInterceptor
method.
builder.Services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.AddInterceptor<LoggingInterceptor>();
The preceding code:
GreeterClient
type.LoggingInterceptor
for this client. LoggingInterceptor
is created once and shared between GreeterClient
instances.By default, an interceptor is created once and shared between clients. This behavior can be overridden by specifying a scope when registering an interceptor. The client factory can be configured to create a new interceptor for each client by specifying InterceptorScope.Client
.
builder.Services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.AddInterceptor<LoggingInterceptor>(InterceptorScope.Client);
Creating client scoped interceptors is useful when an interceptor requires scoped or transient scoped services from DI.
A gRPC interceptor or channel credentials can be used to send Authorization
metadata with each request. For more information about configuring authentication, see Send a bearer token with gRPC client factory.
Additional configuration can be applied to a channel using the ConfigureChannel
method:
builder.Services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.ConfigureChannel(o =>
{
o.Credentials = new CustomCredentials();
});
ConfigureChannel
is passed a GrpcChannelOptions
instance. For more information, see configure client options.
Napomena
Some properties are set on GrpcChannelOptions
before the ConfigureChannel
callback is run:
HttpHandler
is set to the result from ConfigurePrimaryHttpMessageHandler.LoggerFactory
is set to the ILoggerFactory resolved from DI.These values can be overridden by ConfigureChannel
.
An authentication header can be added to gRPC calls using the AddCallCredentials
method:
builder.Services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.AddCallCredentials((context, metadata) =>
{
if (!string.IsNullOrEmpty(_token))
{
metadata.Add("Authorization", $"Bearer {_token}");
}
return Task.CompletedTask;
});
For more information about configuring call credentials, see Bearer token with gRPC client factory.
gRPC clients created by the factory in a gRPC service can be configured with EnableCallContextPropagation()
to automatically propagate the deadline and cancellation token to child calls. The EnableCallContextPropagation()
extension method is available in the Grpc.AspNetCore.Server.ClientFactory NuGet package.
Call context propagation works by reading the deadline and cancellation token from the current gRPC request context and automatically propagating them to outgoing calls made by the gRPC client. Call context propagation is an excellent way of ensuring that complex, nested gRPC scenarios always propagate the deadline and cancellation.
builder.Services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.EnableCallContextPropagation();
By default, EnableCallContextPropagation
raises an error if the client is used outside the context of a gRPC call. The error is designed to alert you that there isn't a call context to propagate. If you want to use the client outside of a call context, suppress the error when the client is configured with SuppressContextNotFoundErrors
:
builder.Services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.EnableCallContextPropagation(o => o.SuppressContextNotFoundErrors = true);
For more information about deadlines and RPC cancellation, see Reliable gRPC services with deadlines and cancellation.
Typically, a gRPC client type is registered once and then injected directly into a type's constructor by DI. However, there are scenarios where it's useful to have multiple configurations for one client. For example, a client that makes gRPC calls with and without authentication.
Multiple clients with the same type can be registered by giving each client a name. Each named client can have its own configuration. The generic AddGrpcClient
extension method has an overload that includes a name parameter:
builder.Services
.AddGrpcClient<Greeter.GreeterClient>("Greeter", o =>
{
o.Address = new Uri("https://localhost:5001");
});
builder.Services
.AddGrpcClient<Greeter.GreeterClient>("GreeterAuthenticated", o =>
{
o.Address = new Uri("https://localhost:5001");
})
.ConfigureChannel(o =>
{
o.Credentials = new CustomCredentials();
});
The preceding code:
GreeterClient
type twice, specifying a unique name for each.GreeterAuthenticated
registration adds credentials to the channel so that gRPC calls made with it are authenticated.A named gRPC client is created in app code using GrpcClientFactory
. The type and name of the desired client is specified using the generic GrpcClientFactory.CreateClient
method:
public class AggregatorService : Aggregator.AggregatorBase
{
private readonly Greeter.GreeterClient _client;
public AggregatorService(GrpcClientFactory grpcClientFactory)
{
_client = grpcClientFactory.CreateClient<Greeter.GreeterClient>("GreeterAuthenticated");
}
}
gRPC integration with HttpClientFactory
offers a centralized way to create gRPC clients. It can be used as an alternative to configuring stand-alone gRPC client instances. Factory integration is available in the Grpc.Net.ClientFactory NuGet package.
The factory offers the following benefits:
HttpClientMessageHandler
To register a gRPC client, the generic AddGrpcClient
extension method can be used within Startup.ConfigureServices
, specifying the gRPC typed client class and service address:
services.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
});
The gRPC client type is registered as transient with dependency injection (DI). The client can now be injected and consumed directly in types created by DI. ASP.NET Core MVC controllers, SignalR hubs and gRPC services are places where gRPC clients can automatically be injected:
public class AggregatorService : Aggregator.AggregatorBase
{
private readonly Greeter.GreeterClient _client;
public AggregatorService(Greeter.GreeterClient client)
{
_client = client;
}
public override async Task SayHellos(HelloRequest request,
IServerStreamWriter<HelloReply> responseStream, ServerCallContext context)
{
// Forward the call on to the greeter service
using (var call = _client.SayHellos(request))
{
await foreach (var response in call.ResponseStream.ReadAllAsync())
{
await responseStream.WriteAsync(response);
}
}
}
}
HttpClientFactory
creates the HttpMessageHandler
used by the gRPC client. Standard HttpClientFactory
methods can be used to add outgoing request middleware or to configure the underlying HttpClientHandler
of the HttpClient
:
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.ConfigurePrimaryHttpMessageHandler(() =>
{
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(LoadCertificate());
return handler;
});
For more information, see Make HTTP requests using IHttpClientFactory.
gRPC interceptors can be added to clients using the AddInterceptor
method.
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.AddInterceptor<LoggingInterceptor>();
The preceding code:
GreeterClient
type.LoggingInterceptor
for this client. LoggingInterceptor
is created once and shared between GreeterClient
instances.By default, an interceptor is created once and shared between clients. This behavior can be overridden by specifying a scope when registering an interceptor. The client factory can be configured to create a new interceptor for each client by specifying InterceptorScope.Client
.
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.AddInterceptor<LoggingInterceptor>(InterceptorScope.Client);
Creating client scoped interceptors is useful when an interceptor requires scoped or transient scoped services from DI.
A gRPC interceptor or channel credentials can be used to send Authorization
metadata with each request. For more information about configuring authentication, see Send a bearer token with gRPC client factory.
Additional configuration can be applied to a channel using the ConfigureChannel
method:
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.ConfigureChannel(o =>
{
o.Credentials = new CustomCredentials();
});
ConfigureChannel
is passed a GrpcChannelOptions
instance. For more information, see configure client options.
Napomena
Some properties are set on GrpcChannelOptions
before the ConfigureChannel
callback is run:
HttpHandler
is set to the result from ConfigurePrimaryHttpMessageHandler.LoggerFactory
is set to the ILoggerFactory resolved from DI.These values can be overridden by ConfigureChannel
.
gRPC clients created by the factory in a gRPC service can be configured with EnableCallContextPropagation()
to automatically propagate the deadline and cancellation token to child calls. The EnableCallContextPropagation()
extension method is available in the Grpc.AspNetCore.Server.ClientFactory NuGet package.
Call context propagation works by reading the deadline and cancellation token from the current gRPC request context and automatically propagating them to outgoing calls made by the gRPC client. Call context propagation is an excellent way of ensuring that complex, nested gRPC scenarios always propagate the deadline and cancellation.
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.EnableCallContextPropagation();
By default, EnableCallContextPropagation
raises an error if the client is used outside the context of a gRPC call. The error is designed to alert you that there isn't a call context to propagate. If you want to use the client outside of a call context, suppress the error when the client is configured with SuppressContextNotFoundErrors
:
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.EnableCallContextPropagation(o => o.SuppressContextNotFoundErrors = true);
For more information about deadlines and RPC cancellation, see Reliable gRPC services with deadlines and cancellation.
Typically, a gRPC client type is registered once and then injected directly into a type's constructor by DI. However, there are scenarios where it is useful to have multiple configurations for one client. For example, a client that makes gRPC calls with and without authentication.
Multiple clients with the same type can be registered by giving each client a name. Each named client can have its own configuration. The generic AddGrpcClient
extension method has an overload that includes a name parameter:
services
.AddGrpcClient<Greeter.GreeterClient>("Greeter", o =>
{
o.Address = new Uri("https://localhost:5001");
});
services
.AddGrpcClient<Greeter.GreeterClient>("GreeterAuthenticated", o =>
{
o.Address = new Uri("https://localhost:5001");
})
.ConfigureChannel(o =>
{
o.Credentials = new CustomCredentials();
});
The preceding code:
GreeterClient
type twice, specifying a unique name for each.GreeterAuthenticated
registration adds credentials to the channel so that gRPC calls made with it are authenticated.A named gRPC client is created in app code using GrpcClientFactory
. The type and name of the desired client is specified using the generic GrpcClientFactory.CreateClient
method:
public class AggregatorService : Aggregator.AggregatorBase
{
private readonly Greeter.GreeterClient _client;
public AggregatorService(GrpcClientFactory grpcClientFactory)
{
_client = grpcClientFactory.CreateClient<Greeter.GreeterClient>("GreeterAuthenticated");
}
}
Povratne informacije za ASP.NET Core
ASP.NET Core je projekat otvorenog koda. Izaberite vezu da biste pružili povratne informacije:
Događaj
Power BI DataViz Svetsko prvenstvo
14. feb 16 - 31. mar 16
Sa 4 šanse za ulazak, možete osvojiti konferencijski paket i stići do LIVE Grand Finale u Las Vegasu
Saznajte višeObuka
Modul
Configure services with dependency injection in ASP.NET Core - Training
Understand and implement dependency injection in an ASP.NET Core app. Use ASP.NET Core's built-in service container to manage dependencies. Register services with the service container.
Dokumentacija
Call gRPC services with the .NET client
Learn how to call gRPC services with the .NET gRPC client.
Transient fault handling with gRPC retries
Learn how to make resilient, fault tolerant gRPC calls with retries in .NET.
Code-first gRPC services and clients with .NET
Learn the basic concepts when writing code-first gRPC with .NET.
Performance best practices with gRPC
Learn the best practices for building high-performance gRPC services.