diff --git a/src/Grpc.AspNetCore.Server/Grpc.AspNetCore.Server.csproj b/src/Grpc.AspNetCore.Server/Grpc.AspNetCore.Server.csproj index 702b8b533..18e2e5691 100644 --- a/src/Grpc.AspNetCore.Server/Grpc.AspNetCore.Server.csproj +++ b/src/Grpc.AspNetCore.Server/Grpc.AspNetCore.Server.csproj @@ -1,4 +1,4 @@ - + gRPC support for ASP.NET Core @@ -29,6 +29,7 @@ + diff --git a/src/Grpc.AspNetCore.Server/GrpcServiceExtensions.cs b/src/Grpc.AspNetCore.Server/GrpcServiceExtensions.cs index fe44d7d04..2bd69c1b0 100644 --- a/src/Grpc.AspNetCore.Server/GrpcServiceExtensions.cs +++ b/src/Grpc.AspNetCore.Server/GrpcServiceExtensions.cs @@ -16,10 +16,12 @@ #endregion +using System.Diagnostics.CodeAnalysis; using Grpc.AspNetCore.Server; using Grpc.AspNetCore.Server.Internal; using Grpc.AspNetCore.Server.Model; using Grpc.AspNetCore.Server.Model.Internal; +using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; @@ -65,11 +67,7 @@ public static IGrpcServerBuilder AddGrpc(this IServiceCollection services) { // Unimplemented constraint is added to the route as an inline constraint to avoid RoutePatternFactory.Parse overload that includes parameter policies. That overload infers strings as regex constraints, which brings in // the regex engine when publishing trimmed or AOT apps. This change reduces Native AOT gRPC server app size by about 1 MB. -#if NET7_0_OR_GREATER - options.SetParameterPolicy(GrpcServerConstants.GrpcUnimplementedConstraintPrefix); -#else - options.ConstraintMap[GrpcServerConstants.GrpcUnimplementedConstraintPrefix] = typeof(GrpcUnimplementedConstraint); -#endif + AddParameterPolicy(options, GrpcServerConstants.GrpcUnimplementedConstraintPrefix); }); services.AddOptions(); services.TryAddSingleton(); @@ -84,6 +82,17 @@ public static IGrpcServerBuilder AddGrpc(this IServiceCollection services) services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IServiceMethodProvider<>), typeof(BinderServiceMethodProvider<>))); return new GrpcServerBuilder(services); + + // This ensures the policy's constructors are preserved in .NET 6 with trimming. Remove when .NET 6 is no longer supported. + static void AddParameterPolicy<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(RouteOptions options, string name) + where T : IParameterPolicy + { +#if NET7_0_OR_GREATER + options.SetParameterPolicy(name); +#else + options.ConstraintMap[name] = typeof(T); +#endif + } } /// diff --git a/src/Grpc.Core.Api/Grpc.Core.Api.csproj b/src/Grpc.Core.Api/Grpc.Core.Api.csproj index 6b697e831..a05267a25 100755 --- a/src/Grpc.Core.Api/Grpc.Core.Api.csproj +++ b/src/Grpc.Core.Api/Grpc.Core.Api.csproj @@ -16,6 +16,8 @@ + + diff --git a/src/Grpc.Core.Api/Internal/CodeAnalysisAttributes.cs b/src/Shared/CodeAnalysisAttributes.cs similarity index 100% rename from src/Grpc.Core.Api/Internal/CodeAnalysisAttributes.cs rename to src/Shared/CodeAnalysisAttributes.cs