-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
DependencyInjectionGenerator.cs
95 lines (83 loc) · 3.39 KB
/
DependencyInjectionGenerator.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
85
86
87
88
89
90
91
92
93
94
95
using System.Text;
namespace Refitter.Core;
internal static class DependencyInjectionGenerator
{
public static string Generate(
RefitGeneratorSettings settings,
string[] interfaceNames)
{
var iocSettings = settings.DependencyInjectionSettings;
if (iocSettings is null || !interfaceNames.Any())
return string.Empty;
var code = new StringBuilder();
var methodDeclaration = string.IsNullOrEmpty(iocSettings.BaseUrl)
? "public static IServiceCollection ConfigureRefitClients(this IServiceCollection services, Uri baseUrl)"
: "public static IServiceCollection ConfigureRefitClients(this IServiceCollection services)";
var configureRefitClient = string.IsNullOrEmpty(iocSettings.BaseUrl)
? ".ConfigureHttpClient(c => c.BaseAddress = baseUrl)"
: $".ConfigureHttpClient(c => c.BaseAddress = new Uri(\"{iocSettings.BaseUrl}\"))";
var usings = iocSettings.UsePolly
? """
using System;
using Microsoft.Extensions.DependencyInjection;
using Polly;
using Polly.Contrib.WaitAndRetry;
using Polly.Extensions.Http;
"""
: """
using System;
using Microsoft.Extensions.DependencyInjection;
""";
code.AppendLine();
code.AppendLine();
code.AppendLine(
$$""""
namespace {{settings.Namespace}}
{
{{usings}}
public static partial class IServiceCollectionExtensions
{
{{methodDeclaration}}
{
"""");
foreach (var interfaceName in interfaceNames)
{
code.Append(
$$"""
services
.AddRefitClient<{{interfaceName}}>()
{{configureRefitClient}}
""");
foreach (string httpMessageHandler in iocSettings.HttpMessageHandlers)
{
code.AppendLine();
code.Append($" .AddHttpMessageHandler<{httpMessageHandler}>()");
}
if (iocSettings.UsePolly)
{
code.AppendLine();
code.Append(
$$"""
.AddPolicyHandler(
HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(
Backoff.DecorrelatedJitterBackoffV2(
TimeSpan.FromSeconds({{iocSettings.FirstBackoffRetryInSeconds}}),
{{iocSettings.PollyMaxRetryCount}}))
""");
}
code.Append(");");
code.AppendLine();
code.AppendLine();
}
code.Remove(code.Length - 2, 2);
code.AppendLine();
code.AppendLine(" return services;");
code.AppendLine(" }");
code.AppendLine(" }");
code.AppendLine("}");
code.AppendLine();
return code.ToString();
}
}