-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
RegistrationsBuilder.cs
58 lines (51 loc) · 1.82 KB
/
RegistrationsBuilder.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
using System.Text;
using Havit.SourceGenerators.StrongApiStringLocalizers;
namespace LocalizerGenerator;
internal class RegistrationsBuilder
{
public string Namespace { get; set; }
public List<LocalizerBuilder> Localizers { get; } = new List<LocalizerBuilder>();
public string MethodName => "AddGeneratedResourceWrappers";
public string BuildSource()
{
var builder = new StringBuilder();
BuildNamespace(builder);
return builder.ToString();
}
private void BuildNamespace(StringBuilder builder)
{
builder.Append("namespace ").Append(Namespace).AppendLine();
builder.AppendLine("{");
BuildUsings(builder);
BuildClass(builder);
builder.AppendLine("}");
}
private void BuildUsings(StringBuilder builder)
{
builder.AppendLine("using System.CodeDom.Compiler;");
builder.AppendLine("using Microsoft.Extensions.DependencyInjection;");
builder.AppendLine("using Microsoft.Extensions.Localization;");
foreach (var @namespace in Localizers.Select(x => x.Namespace).Distinct(StringComparer.Ordinal))
{
builder.Append("using ").Append(@namespace).Append(";").AppendLine();
}
}
private void BuildClass(StringBuilder builder)
{
builder.AppendGeneratedCodeAttribute().AppendLine();
builder.Append("partial class ").Append(LocalizerGenerator.ServiceCollectionInstallerMarker).AppendLine();
builder.AppendLine("{");
builder.Append("public static void ").Append(MethodName).Append("(this IServiceCollection services)").AppendLine();
builder.AppendLine("{");
BuildRegistrations(builder);
builder.AppendLine("}");
builder.AppendLine("}");
}
private void BuildRegistrations(StringBuilder builder)
{
foreach (var localizer in Localizers)
{
builder.Append("services.AddScoped<").Append(localizer.LocalizerInterfaceName).Append(", ").Append(localizer.LocalizerClassName).Append(">();").AppendLine();
}
}
}