Skip to content

Commit 347a627

Browse files
committed
aot实验
1 parent 923504f commit 347a627

File tree

19 files changed

+167
-41
lines changed

19 files changed

+167
-41
lines changed

App/Startup.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,7 @@ public void ConfigureServices(IServiceCollection services)
4949
services
5050
.AddWebApiClient()
5151
.UseJsonFirstApiActionDescriptor()
52-
.UseSourceGeneratorHttpApiActivator()
53-
.AddDynamicDependencyApp();
52+
.UseSourceGeneratorHttpApiActivator();
5453

5554
// 注册userApi
5655
services.AddHttpApi(typeof(IUserApi), o =>

AppAot/AppAot.csproj

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net8.0</TargetFramework>
6+
<GeneratePackageOnBuild>false</GeneratePackageOnBuild>
7+
<Nullable>enable</Nullable>
8+
<PublishTrimmed>true</PublishTrimmed>
9+
<PublishAot>true</PublishAot>
10+
<InvariantGlobalization>true</InvariantGlobalization>
11+
</PropertyGroup>
12+
13+
<ItemGroup>
14+
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
15+
</ItemGroup>
16+
17+
<ItemGroup>
18+
<ProjectReference Include="..\WebApiClientCore.Extensions.SourceGenerator\WebApiClientCore.Extensions.SourceGenerator.csproj" />
19+
<ProjectReference Include="..\WebApiClientCore\WebApiClientCore.csproj" />
20+
<ProjectReference Include="..\WebApiClientCore.Analyzers\WebApiClientCore.Analyzers.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
21+
<ProjectReference Include="..\WebApiClientCore.Analyzers.SourceGenerator\WebApiClientCore.Analyzers.SourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
22+
</ItemGroup>
23+
24+
</Project>

AppAot/AppData.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
namespace AppAot
2+
{
3+
public class AppData
4+
{
5+
public string? WebpackCompilationHash { get; set; }
6+
}
7+
}

AppAot/AppHostedService.cs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
using Microsoft.Extensions.DependencyInjection;
2+
using Microsoft.Extensions.Hosting;
3+
using Microsoft.Extensions.Logging;
4+
using System;
5+
using System.Collections.Generic;
6+
using System.Linq;
7+
using System.Text;
8+
using System.Threading;
9+
using System.Threading.Tasks;
10+
11+
namespace AppAot
12+
{
13+
class AppHostedService : BackgroundService
14+
{
15+
private readonly IServiceScopeFactory serviceScopeFactory;
16+
private readonly ILogger<AppHostedService> logger;
17+
18+
public AppHostedService(
19+
IServiceScopeFactory serviceScopeFactory,
20+
ILogger<AppHostedService> logger)
21+
{
22+
this.serviceScopeFactory = serviceScopeFactory;
23+
this.logger = logger;
24+
}
25+
26+
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
27+
{
28+
using var scope = this.serviceScopeFactory.CreateScope();
29+
var api = scope.ServiceProvider.GetRequiredService<ICloudflareApi>();
30+
var appData = await api.GetAppDataAsync();
31+
this.logger.LogInformation($"WebpackCompilationHash: {appData.WebpackCompilationHash}");
32+
}
33+
}
34+
}

AppAot/AppJsonSerializerContext.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
using System.Text.Json.Serialization;
2+
3+
namespace AppAot
4+
{
5+
[JsonSerializable(typeof(AppData[]))]
6+
partial class AppJsonSerializerContext : JsonSerializerContext
7+
{
8+
}
9+
}

AppAot/ICloudflareApi.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using System.Threading.Tasks;
2+
using WebApiClientCore.Attributes;
3+
4+
namespace AppAot
5+
{
6+
[HttpHost("https://www.cloudflare-cn.com")]
7+
[LoggingFilter]
8+
public interface ICloudflareApi
9+
{
10+
[HttpGet("/page-data/app-data.json")]
11+
Task<AppData> GetAppDataAsync();
12+
}
13+
}

AppAot/Program.cs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using Microsoft.Extensions.DependencyInjection;
2+
using Microsoft.Extensions.Hosting;
3+
4+
namespace AppAot
5+
{
6+
class Program
7+
{
8+
static void Main(string[] args)
9+
{
10+
Host.CreateDefaultBuilder(args)
11+
.ConfigureServices(services =>
12+
{
13+
services
14+
.AddWebApiClient()
15+
.UseSourceGeneratorHttpApiActivator() // SG 激活器
16+
.ConfigureHttpApi(options => // json SG生成器配置
17+
{
18+
var jsonContext = AppJsonSerializerContext.Default;
19+
options.JsonSerializeOptions.TypeInfoResolverChain.Insert(0, jsonContext);
20+
options.JsonDeserializeOptions.TypeInfoResolverChain.Insert(0, jsonContext);
21+
options.KeyValueSerializeOptions.GetJsonSerializerOptions().TypeInfoResolverChain.Insert(0, jsonContext);
22+
});
23+
24+
services.AddHttpApi<ICloudflareApi>();
25+
services.AddHostedService<AppHostedService>();
26+
})
27+
.Build()
28+
.Run();
29+
}
30+
}
31+
}

WebApiClientCore.Abstractions/IHttpApiActivator.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@
44
/// 定义THttpApi的实例创建器的接口
55
/// </summary>
66
/// <typeparam name="THttpApi"></typeparam>
7-
public interface IHttpApiActivator<THttpApi>
7+
public interface IHttpApiActivator<
8+
#if NET5_0_OR_GREATER
9+
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)]
10+
#endif
11+
THttpApi>
812
{
913
/// <summary>
1014
/// 创建THttpApi的代理实例

WebApiClientCore.Abstractions/WebApiClientCore.Abstractions.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<Nullable>enable</Nullable>
5-
<TargetFramework>netstandard2.1</TargetFramework>
5+
<TargetFrameworks>netstandard2.1;net5.0</TargetFrameworks>
66

77
<RootNamespace>WebApiClientCore</RootNamespace>
88
<AssemblyName>WebApiClientCore.Abstractions</AssemblyName>
Lines changed: 9 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using Microsoft.CodeAnalysis;
22
using Microsoft.CodeAnalysis.Text;
33
using System.Collections.Generic;
4-
using System.Linq;
54
using System.Text;
65

76
namespace WebApiClientCore.Analyzers.SourceGenerator
@@ -11,8 +10,8 @@ sealed class DynamicDependencyBuilder
1110
private readonly Compilation compilation;
1211
private readonly IEnumerable<HttpApiCodeBuilder> codeBuilders;
1312

14-
public string FileName => "WebApiClientBuilderExtensions.g.cs";
15-
public string ClassName => "WebApiClientBuilderExtensions_G";
13+
public string FileName => "DynamicDependencyInitializer.g.cs";
14+
public string ClassName => "DynamicDependencyInitializer_G";
1615

1716
public DynamicDependencyBuilder(Compilation compilation, IEnumerable<HttpApiCodeBuilder> codeBuilders)
1817
{
@@ -35,47 +34,33 @@ public override string ToString()
3534
var builder = new StringBuilder();
3635
builder.AppendLine("#if NET5_0_OR_GREATER");
3736
builder.AppendLine("using System.Diagnostics.CodeAnalysis;");
38-
builder.AppendLine("namespace Microsoft.Extensions.DependencyInjection");
37+
builder.AppendLine("using System.Runtime.CompilerServices;");
38+
builder.AppendLine($"namespace WebApiClientCore");
3939
builder.AppendLine("{");
40-
builder.AppendLine(" /// <summary>IWebApiClientBuilder扩展</summary>");
41-
builder.AppendLine($" public static partial class {this.ClassName}");
40+
builder.AppendLine(" /// <summary>动态依赖初始化器</summary>");
41+
builder.AppendLine($" static partial class {this.ClassName}");
4242
builder.AppendLine(" {");
4343

4444
builder.AppendLine($"""
4545
/// <summary>
4646
/// 注册程序集{compilation.AssemblyName}的所有动态依赖
4747
/// 避免程序集在裁剪时裁剪掉由SourceGenerator生成的代理类
4848
/// </summary>
49-
/// <param name="builder"></param>
50-
/// <returns></returns>
5149
""");
52-
53-
var assemblyName = GetAssemblyName(compilation);
5450
foreach (var codeBuilder in this.codeBuilders)
5551
{
5652
builder.AppendLine($" [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof({codeBuilder.Namespace}.{codeBuilder.ClassName}))]");
5753
}
58-
59-
builder.AppendLine($" public static IWebApiClientBuilder AddDynamicDependency{assemblyName}(this IWebApiClientBuilder builder)");
54+
builder.AppendLine(" [ModuleInitializer]");
55+
builder.AppendLine(" public static void AddDynamicDependency()");
6056
builder.AppendLine(" {");
61-
builder.AppendLine(" return builder;");
6257
builder.AppendLine(" }");
63-
58+
6459
builder.AppendLine(" }");
6560
builder.AppendLine("}");
6661
builder.AppendLine("#endif");
6762
return builder.ToString();
6863
}
6964

70-
private static string GetAssemblyName(Compilation compilation)
71-
{
72-
var assemblyName = compilation.AssemblyName ?? string.Empty;
73-
return new string(assemblyName.Where(IsAllowChar).ToArray());
74-
75-
static bool IsAllowChar(char c)
76-
{
77-
return ('0' <= c && c <= '9') || ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
78-
}
79-
}
8065
}
8166
}

0 commit comments

Comments
 (0)