-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApplicationBuilderExtensions.cs
84 lines (74 loc) · 2.53 KB
/
ApplicationBuilderExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System.Reflection;
using Grpc.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Nerosoft.Euonia.Grpc;
namespace Microsoft.AspNetCore.Builder;
/// <summary>
/// Extension methods for <see cref="IApplicationBuilder"/> to add gRPC server features.
/// </summary>
public static class ApplicationBuilderExtensions
{
/// <summary>
///
/// </summary>
/// <param name="builder"></param>
/// <param name="configure"></param>
/// <returns></returns>
public static IApplicationBuilder UseGrpcEndpoints(this IApplicationBuilder builder, Action<IEndpointRouteBuilder> configure = null)
{
builder.UseEndpoints(endpoints =>
{
endpoints.MapGrpcServices();
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Communication with gRPC endpoints must be called through a gRPC client");
});
configure?.Invoke(endpoints);
});
return builder;
}
/// <summary>
///
/// </summary>
/// <param name="builder"></param>
/// <param name="useHealthCheck"></param>
public static void MapGrpcServices(this IEndpointRouteBuilder builder, bool useHealthCheck = true)
{
if (useHealthCheck)
{
builder.UseGrpcHealthCheck();
}
var method = typeof(GrpcEndpointRouteBuilderExtensions).GetMethod(nameof(GrpcEndpointRouteBuilderExtensions.MapGrpcService));
if (method == null)
{
return;
}
var definedTypes = Assembly.GetEntryAssembly()?.DefinedTypes;
if (definedTypes == null)
{
return;
}
var types = definedTypes.Where(t => t.IsClass)
.Where(t => t.IsAbstract == false)
.Where(t => t.BaseType != null && t.BaseType.IsAbstract)
.Where(t => t.BaseType.GetCustomAttributes<BindServiceMethodAttribute>().Any());
foreach (var type in types)
{
method.MakeGenericMethod(type.AsType()).Invoke(null, new object[] { builder });
}
}
/// <summary>
///
/// </summary>
/// <param name="builder"></param>
/// <exception cref="ArgumentNullException"></exception>
public static void UseGrpcHealthCheck(this IEndpointRouteBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.MapGrpcService<HealthService>();
}
}