Skip to content

Update gRPC shared code #62340

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Grpc.AspNetCore.Server;
using Grpc.AspNetCore.Server.Model;
using Grpc.Shared;
using Grpc.Shared.Server;
using Microsoft.AspNetCore.Grpc.JsonTranscoding;
using Microsoft.AspNetCore.Grpc.JsonTranscoding.Internal.Binding;
using Microsoft.Extensions.DependencyInjection.Extensions;
Expand All @@ -28,6 +29,7 @@ public static IGrpcServerBuilder AddJsonTranscoding(this IGrpcServerBuilder buil
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IServiceMethodProvider<>), typeof(JsonTranscodingServiceMethodProvider<>)));
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<GrpcJsonTranscodingOptions>, GrpcJsonTranscodingOptionsSetup>());
builder.Services.TryAddSingleton<DescriptorRegistry>();
builder.Services.TryAddSingleton<InterceptorActivators>();

return builder;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ private delegate (RequestDelegate RequestDelegate, List<object> Metadata) Create
private readonly GrpcServiceOptions<TService> _serviceOptions;
private readonly IGrpcServiceActivator<TService> _serviceActivator;
private readonly GrpcJsonTranscodingOptions _jsonTranscodingOptions;
private readonly InterceptorActivators _interceptorActivators;
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger _logger;

Expand All @@ -45,7 +46,8 @@ internal JsonTranscodingProviderServiceBinder(
GrpcServiceOptions<TService> serviceOptions,
ILoggerFactory loggerFactory,
IGrpcServiceActivator<TService> serviceActivator,
GrpcJsonTranscodingOptions jsonTranscodingOptions)
GrpcJsonTranscodingOptions jsonTranscodingOptions,
InterceptorActivators interceptorActivators)
{
_context = context;
_invokerResolver = invokerResolver;
Expand All @@ -54,6 +56,7 @@ internal JsonTranscodingProviderServiceBinder(
_serviceOptions = serviceOptions;
_serviceActivator = serviceActivator;
_jsonTranscodingOptions = jsonTranscodingOptions;
_interceptorActivators = interceptorActivators;
_loggerFactory = loggerFactory;
_logger = loggerFactory.CreateLogger<JsonTranscodingProviderServiceBinder<TService>>();
}
Expand Down Expand Up @@ -162,7 +165,7 @@ private void ProcessHttpRule<TRequest, TResponse>(
httpRule,
methodDescriptor);

var methodInvoker = new UnaryServerMethodInvoker<TService, TRequest, TResponse>(invoker, method, methodOptions, _serviceActivator);
var methodInvoker = new UnaryServerMethodInvoker<TService, TRequest, TResponse>(invoker, method, methodOptions, _serviceActivator, _interceptorActivators);
var callHandler = new UnaryServerCallHandler<TService, TRequest, TResponse>(
methodInvoker,
_loggerFactory,
Expand All @@ -189,7 +192,7 @@ private void ProcessHttpRule<TRequest, TResponse>(
httpRule,
methodDescriptor);

var methodInvoker = new ServerStreamingServerMethodInvoker<TService, TRequest, TResponse>(invoker, method, methodOptions, _serviceActivator);
var methodInvoker = new ServerStreamingServerMethodInvoker<TService, TRequest, TResponse>(invoker, method, methodOptions, _serviceActivator, _interceptorActivators);
var callHandler = new ServerStreamingServerCallHandler<TService, TRequest, TResponse>(
methodInvoker,
_loggerFactory,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,16 @@ internal sealed partial class JsonTranscodingServiceMethodProvider<TService> : I
private readonly ILoggerFactory _loggerFactory;
private readonly IGrpcServiceActivator<TService> _serviceActivator;
private readonly DescriptorRegistry _serviceDescriptorRegistry;
private readonly InterceptorActivators _interceptorActivators;

public JsonTranscodingServiceMethodProvider(
ILoggerFactory loggerFactory,
IOptions<GrpcServiceOptions> globalOptions,
IOptions<GrpcServiceOptions<TService>> serviceOptions,
IGrpcServiceActivator<TService> serviceActivator,
IOptions<GrpcJsonTranscodingOptions> jsonTranscodingOptions,
DescriptorRegistry serviceDescriptorRegistry)
DescriptorRegistry serviceDescriptorRegistry,
InterceptorActivators interceptorActivators)
{
_logger = loggerFactory.CreateLogger<JsonTranscodingServiceMethodProvider<TService>>();
_globalOptions = globalOptions.Value;
Expand All @@ -36,6 +38,7 @@ public JsonTranscodingServiceMethodProvider(
_loggerFactory = loggerFactory;
_serviceActivator = serviceActivator;
_serviceDescriptorRegistry = serviceDescriptorRegistry;
_interceptorActivators = interceptorActivators;
}

public void OnServiceMethodDiscovery(ServiceMethodProviderContext<TService> context)
Expand Down Expand Up @@ -70,7 +73,8 @@ public void OnServiceMethodDiscovery(ServiceMethodProviderContext<TService> cont
_serviceOptions,
_loggerFactory,
_serviceActivator,
_jsonTranscodingOptions);
_jsonTranscodingOptions,
_interceptorActivators);

try
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Description>HTTP API for gRPC ASP.NET Core</Description>
<PackageTags>gRPC RPC HTTP/2 REST</PackageTags>
Expand All @@ -18,6 +18,8 @@
<Compile Include="..\Shared\Server\ServerMethodInvokerBase.cs" Link="Internal\Shared\Server\ServerMethodInvokerBase.cs" />
<Compile Include="..\Shared\Server\ServerStreamingServerMethodInvoker.cs" Link="Internal\Shared\Server\ServerStreamingServerMethodInvoker.cs" />
<Compile Include="..\Shared\Server\UnaryServerMethodInvoker.cs" Link="Internal\Shared\Server\UnaryServerMethodInvoker.cs" />
<Compile Include="..\Shared\Server\ServerDynamicAccessConstants.cs" Link="Internal\Shared\Server\ServerDynamicAccessConstants.cs" />
<Compile Include="..\Shared\Server\InterceptorActivators.cs" Link="Internal\Shared\Server\InterceptorActivators.cs" />
<Compile Include="..\Shared\DescriptorRegistry.cs" Link="Internal\Shared\DescriptorRegistry.cs" />
<Compile Include="..\Shared\AuthContextHelpers.cs" Link="Internal\Shared\AuthContextHelpers.cs" />
<Compile Include="..\Shared\ServiceDescriptorHelpers.cs" Link="Internal\Shared\ServiceDescriptorHelpers.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

#endregion

using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Grpc.Core;

Expand Down Expand Up @@ -64,6 +65,8 @@ internal static class BindMethodFinder
return null;
}

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern",
Justification = "Fallback doesn't have BindServiceMethodAttribute so can't be verified.")]
internal static MethodInfo? GetBindMethodFallback(Type serviceType)
{
// Search for the generated service base class
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

#endregion

using System.Diagnostics.CodeAnalysis;
using Grpc.AspNetCore.Server;
using Grpc.AspNetCore.Server.Model;
using Grpc.Core;
Expand All @@ -29,7 +30,7 @@ namespace Grpc.Shared.Server;
/// <typeparam name="TService">Service type for this method.</typeparam>
/// <typeparam name="TRequest">Request message type for this method.</typeparam>
/// <typeparam name="TResponse">Response message type for this method.</typeparam>
internal sealed class ClientStreamingServerMethodInvoker<TService, TRequest, TResponse> : ServerMethodInvokerBase<TService, TRequest, TResponse>
internal sealed class ClientStreamingServerMethodInvoker<[DynamicallyAccessedMembers(ServerDynamicAccessConstants.ServiceAccessibility)] TService, TRequest, TResponse> : ServerMethodInvokerBase<TService, TRequest, TResponse>
where TRequest : class
where TResponse : class
where TService : class
Expand All @@ -44,18 +45,20 @@ internal sealed class ClientStreamingServerMethodInvoker<TService, TRequest, TRe
/// <param name="method">The description of the gRPC method.</param>
/// <param name="options">The options used to execute the method.</param>
/// <param name="serviceActivator">The service activator used to create service instances.</param>
/// <param name="interceptorActivators">The interceptor activators used to create interceptor instances.</param>
public ClientStreamingServerMethodInvoker(
ClientStreamingServerMethod<TService, TRequest, TResponse> invoker,
Method<TRequest, TResponse> method,
MethodOptions options,
IGrpcServiceActivator<TService> serviceActivator)
IGrpcServiceActivator<TService> serviceActivator,
InterceptorActivators interceptorActivators)
: base(method, options, serviceActivator)
{
_invoker = invoker;

if (Options.HasInterceptors)
{
var interceptorPipeline = new InterceptorPipelineBuilder<TRequest, TResponse>(Options.Interceptors);
var interceptorPipeline = new InterceptorPipelineBuilder<TRequest, TResponse>(Options.Interceptors, interceptorActivators);
_pipelineInvoker = interceptorPipeline.ClientStreamingPipeline(ResolvedInterceptorInvoker);
}
}
Expand All @@ -65,7 +68,7 @@ private async Task<TResponse> ResolvedInterceptorInvoker(IAsyncStreamReader<TReq
GrpcActivatorHandle<TService> serviceHandle = default;
try
{
serviceHandle = ServiceActivator.Create(resolvedContext.GetHttpContext().RequestServices);
serviceHandle = CreateServiceHandle(resolvedContext);
return await _invoker(
serviceHandle.Instance,
requestStream,
Expand Down Expand Up @@ -95,7 +98,7 @@ public async Task<TResponse> Invoke(HttpContext httpContext, ServerCallContext s
GrpcActivatorHandle<TService> serviceHandle = default;
try
{
serviceHandle = ServiceActivator.Create(httpContext.RequestServices);
serviceHandle = CreateServiceHandle(httpContext);
return await _invoker(
serviceHandle.Instance,
requestStream,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

#endregion

using System.Diagnostics.CodeAnalysis;
using Grpc.AspNetCore.Server;
using Grpc.AspNetCore.Server.Model;
using Grpc.Core;
Expand All @@ -29,7 +30,7 @@ namespace Grpc.Shared.Server;
/// <typeparam name="TService">Service type for this method.</typeparam>
/// <typeparam name="TRequest">Request message type for this method.</typeparam>
/// <typeparam name="TResponse">Response message type for this method.</typeparam>
internal sealed class DuplexStreamingServerMethodInvoker<TService, TRequest, TResponse> : ServerMethodInvokerBase<TService, TRequest, TResponse>
internal sealed class DuplexStreamingServerMethodInvoker<[DynamicallyAccessedMembers(ServerDynamicAccessConstants.ServiceAccessibility)] TService, TRequest, TResponse> : ServerMethodInvokerBase<TService, TRequest, TResponse>
where TRequest : class
where TResponse : class
where TService : class
Expand All @@ -44,18 +45,20 @@ internal sealed class DuplexStreamingServerMethodInvoker<TService, TRequest, TRe
/// <param name="method">The description of the gRPC method.</param>
/// <param name="options">The options used to execute the method.</param>
/// <param name="serviceActivator">The service activator used to create service instances.</param>
/// <param name="interceptorActivators">The interceptor activators used to create interceptor instances.</param>
public DuplexStreamingServerMethodInvoker(
DuplexStreamingServerMethod<TService, TRequest, TResponse> invoker,
Method<TRequest, TResponse> method,
MethodOptions options,
IGrpcServiceActivator<TService> serviceActivator)
IGrpcServiceActivator<TService> serviceActivator,
InterceptorActivators interceptorActivators)
: base(method, options, serviceActivator)
{
_invoker = invoker;

if (Options.HasInterceptors)
{
var interceptorPipeline = new InterceptorPipelineBuilder<TRequest, TResponse>(Options.Interceptors);
var interceptorPipeline = new InterceptorPipelineBuilder<TRequest, TResponse>(Options.Interceptors, interceptorActivators);
_pipelineInvoker = interceptorPipeline.DuplexStreamingPipeline(ResolvedInterceptorInvoker);
}
}
Expand All @@ -65,7 +68,7 @@ private async Task ResolvedInterceptorInvoker(IAsyncStreamReader<TRequest> reque
GrpcActivatorHandle<TService> serviceHandle = default;
try
{
serviceHandle = ServiceActivator.Create(resolvedContext.GetHttpContext().RequestServices);
serviceHandle = CreateServiceHandle(resolvedContext);
await _invoker(
serviceHandle.Instance,
requestStream,
Expand All @@ -88,15 +91,15 @@ await _invoker(
/// <param name="serverCallContext">The <see cref="ServerCallContext"/>.</param>
/// <param name="requestStream">The <typeparamref name="TRequest"/> reader.</param>
/// <param name="responseStream">The <typeparamref name="TResponse"/> writer.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous method.</returns>
/// <returns>A <see cref="Task{TResponse}"/> that represents the asynchronous method.</returns>
public async Task Invoke(HttpContext httpContext, ServerCallContext serverCallContext, IAsyncStreamReader<TRequest> requestStream, IServerStreamWriter<TResponse> responseStream)
{
if (_pipelineInvoker == null)
{
GrpcActivatorHandle<TService> serviceHandle = default;
try
{
serviceHandle = ServiceActivator.Create(httpContext.RequestServices);
serviceHandle = CreateServiceHandle(httpContext);
await _invoker(
serviceHandle.Instance,
requestStream,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#region Copyright notice and license

// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#endregion

using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using Grpc.AspNetCore.Server;
using Microsoft.Extensions.DependencyInjection;

namespace Grpc.Shared.Server;

internal sealed class InterceptorActivators
{
private readonly ConcurrentDictionary<Type, IGrpcInterceptorActivator> _cachedActivators = new();
private readonly IServiceProvider _serviceProvider;

public InterceptorActivators(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}

public IGrpcInterceptorActivator GetInterceptorActivator(Type type)
{
return _cachedActivators.GetOrAdd<IServiceProvider>(type, CreateActivator, _serviceProvider);
}

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern",
Justification = "Type parameter members are preserved with DynamicallyAccessedMembers on InterceptorRegistration.Type property.")]
[UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode",
Justification = "Type definition is explicitly specified and type argument is always an Interceptor type.")]
private static IGrpcInterceptorActivator CreateActivator(Type type, IServiceProvider serviceProvider)
{
return (IGrpcInterceptorActivator)serviceProvider.GetRequiredService(typeof(IGrpcInterceptorActivator<>).MakeGenericType(type));
}
}
Loading
Loading