From f2033675323d06dd20d24c8e4a91f362ecc810c1 Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Mon, 25 Jul 2022 18:19:11 +0800 Subject: [PATCH 01/13] feat(Caller): Add Caller --- Directory.Build.props | 1 + Masa.Contrib.sln | 74 +++++- src/BuildingBlocks/MASA.BuildingBlocks | 2 +- .../CallerOptionsExtensions.cs | 40 ++++ .../DaprCallerBase.cs | 31 +++ .../DaprCallerProvider.cs | 91 ++++++++ .../DefaultDaprClientBuilder.cs | 17 ++ .../HttpMessageHandlerBuilder.cs | 14 ++ .../IDaprRequestMessage.cs | 9 + ...a.Contrib.Service.Caller.DaprClient.csproj | 17 ++ .../MasaDaprClientBuilder.cs | 70 ++++++ .../MasaDaprClientBuilderExtensions.cs | 48 ++++ .../Options/CallerDaprClientOptions.cs | 9 + .../README.md | 101 ++++++++ .../README.zh-CN.md | 101 ++++++++ .../_Imports.cs | 10 + .../CallerOptionsExtensions.cs | 26 +++ .../HttpClientCallerBase.cs | 32 +++ .../HttpClientCallerProvider.cs | 72 ++++++ ...a.Contrib.Service.Caller.HttpClient.csproj | 17 ++ .../MasaHttpClientBuilder.cs | 62 +++++ .../README.md | 110 +++++++++ .../README.zh-CN.md | 110 +++++++++ .../_Imports.cs | 6 + .../DefaultCallerFactory.cs | 31 +++ .../DefaultRequestIdGenerator.cs | 9 + .../DefaultRequestMessage.cs | 35 +++ .../DefaultResponseMessage.cs | 92 ++++++++ .../DefaultTypeConvertProvider.cs | 98 ++++++++ .../IRequestIdGenerator.cs | 9 + .../Internal/CallerDependExtensions.cs | 89 +++++++ .../Internal/Const.cs | 9 + .../Internal/Options/PropertyInfoMember.cs | 31 +++ .../JsonRequestMessage.cs | 31 +++ .../Masa.Contrib.Service.Caller.csproj | 17 ++ .../Masa.Contrib.Service.Caller/README.md | 36 +++ .../README.zh-CN.md | 36 +++ .../ServiceCollectionExtensions.cs | 108 +++++++++ .../Masa.Contrib.Service.Caller/_Imports.cs | 20 ++ .../Masa.Contrib.Configuration.Tests.csproj | 7 - .../AutomaticCallerTest.cs | 47 ++++ .../CallerTest.cs | 217 ++++++++++++++++++ .../Callers/DaprCaller.cs | 16 ++ .../Callers/GithubCaller.cs | 20 ++ .../Callers/RoleCaller.cs | 11 + .../Callers/UserCaller.cs | 11 + .../Callers/UserDaprCallerBase.cs | 29 +++ ...ervice.Caller.AutomaticCaller.Tests.csproj | 28 +++ .../_Imports.cs | 11 + .../CallerTest.cs | 138 +++++++++++ .../CustomHttpClientCallerProvider.cs | 14 ++ .../DefaultXmlResponseMessage.cs | 91 ++++++++ .../HttpClientCallerTest.cs | 128 +++++++++++ .../Masa.Contrib.Service.Caller.Tests.csproj | 24 ++ .../Queries/UserDetailQuery.cs | 34 +++ .../Queries/UserListQuery.cs | 18 ++ .../Requesties/RegisterUser.cs | 22 ++ .../Response/BaseResponse.cs | 16 ++ .../TypeConvertTest.cs | 30 +++ .../Utils/XmlUtils.cs | 23 ++ .../XmlRequestMessage.cs | 17 ++ .../_Imports.cs | 22 ++ 62 files changed, 2686 insertions(+), 9 deletions(-) create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/CallerOptionsExtensions.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCallerBase.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCallerProvider.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DefaultDaprClientBuilder.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/HttpMessageHandlerBuilder.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/IDaprRequestMessage.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/Masa.Contrib.Service.Caller.DaprClient.csproj create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/MasaDaprClientBuilder.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/MasaDaprClientBuilderExtensions.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/Options/CallerDaprClientOptions.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.md create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/_Imports.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/CallerOptionsExtensions.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCallerBase.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCallerProvider.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/Masa.Contrib.Service.Caller.HttpClient.csproj create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/MasaHttpClientBuilder.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.md create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/_Imports.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/DefaultCallerFactory.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestIdGenerator.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/DefaultResponseMessage.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/DefaultTypeConvertProvider.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/IRequestIdGenerator.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/Internal/CallerDependExtensions.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/Internal/Const.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/Internal/Options/PropertyInfoMember.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/Masa.Contrib.Service.Caller.csproj create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/README.md create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/README.zh-CN.md create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/ServiceCollectionExtensions.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/_Imports.cs create mode 100644 test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/AutomaticCallerTest.cs create mode 100644 test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/CallerTest.cs create mode 100644 test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/DaprCaller.cs create mode 100644 test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/GithubCaller.cs create mode 100644 test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/RoleCaller.cs create mode 100644 test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/UserCaller.cs create mode 100644 test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/UserDaprCallerBase.cs create mode 100644 test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Masa.Contrib.Service.Caller.AutomaticCaller.Tests.csproj create mode 100644 test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/_Imports.cs create mode 100644 test/Masa.Contrib.Service.Caller.Tests/CallerTest.cs create mode 100644 test/Masa.Contrib.Service.Caller.Tests/CustomHttpClientCallerProvider.cs create mode 100644 test/Masa.Contrib.Service.Caller.Tests/DefaultXmlResponseMessage.cs create mode 100644 test/Masa.Contrib.Service.Caller.Tests/HttpClientCallerTest.cs create mode 100644 test/Masa.Contrib.Service.Caller.Tests/Masa.Contrib.Service.Caller.Tests.csproj create mode 100644 test/Masa.Contrib.Service.Caller.Tests/Queries/UserDetailQuery.cs create mode 100644 test/Masa.Contrib.Service.Caller.Tests/Queries/UserListQuery.cs create mode 100644 test/Masa.Contrib.Service.Caller.Tests/Requesties/RegisterUser.cs create mode 100644 test/Masa.Contrib.Service.Caller.Tests/Response/BaseResponse.cs create mode 100644 test/Masa.Contrib.Service.Caller.Tests/TypeConvertTest.cs create mode 100644 test/Masa.Contrib.Service.Caller.Tests/Utils/XmlUtils.cs create mode 100644 test/Masa.Contrib.Service.Caller.Tests/XmlRequestMessage.cs create mode 100644 test/Masa.Contrib.Service.Caller.Tests/_Imports.cs diff --git a/Directory.Build.props b/Directory.Build.props index fc9ddd6b2..5e960cf2c 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -9,6 +9,7 @@ 0.5.0-rc.1 7.3.0 1.5.0 + 3.19.1 1.0.4 1.3.0 diff --git a/Masa.Contrib.sln b/Masa.Contrib.sln index ed5b7b774..71f31e753 100644 --- a/Masa.Contrib.sln +++ b/Masa.Contrib.sln @@ -324,6 +324,22 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.BasicAbility.T EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.BasicAbility.Tsc", "src\BuildingBlocks\MASA.BuildingBlocks\src\BasicAbility\Masa.BuildingBlocks.BasicAbility.Tsc\Masa.BuildingBlocks.BasicAbility.Tsc.csproj", "{C265268A-F311-4B6A-915E-C1AF9D1EB624}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.BuildingBlocks.Service.Caller", "src\BuildingBlocks\MASA.BuildingBlocks\src\Service\Masa.BuildingBlocks.Service.Caller\Masa.BuildingBlocks.Service.Caller.csproj", "{ABF6E41A-CBF9-49DE-87FC-9D88F440A104}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Caller", "Caller", "{F9DDEB6F-25F8-4505-8300-2E247564BD8B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.Service.Caller.DaprClient", "src\Service\Caller\Masa.Contrib.Service.Caller.DaprClient\Masa.Contrib.Service.Caller.DaprClient.csproj", "{1CDA9001-A29F-4EBE-BBEA-0B2E663B9A19}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.Service.Caller.HttpClient", "src\Service\Caller\Masa.Contrib.Service.Caller.HttpClient\Masa.Contrib.Service.Caller.HttpClient.csproj", "{00659C82-2E23-4E8F-BA34-EC41D78C87A1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.Service.Caller", "src\Service\Caller\Masa.Contrib.Service.Caller\Masa.Contrib.Service.Caller.csproj", "{28893415-0789-4FBB-A8B7-F0F9260CEDE3}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Service", "Service", "{4AA6B450-D4AA-4474-9ECF-52A44935D8D9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.Service.Caller.Tests", "test\Masa.Contrib.Service.Caller.Tests\Masa.Contrib.Service.Caller.Tests.csproj", "{D855894E-4C72-41DC-8F84-EF66CDE37453}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.Service.Caller.AutomaticCaller.Tests", "test\Masa.Contrib.Service.Caller.AutomaticCaller.Tests\Masa.Contrib.Service.Caller.AutomaticCaller.Tests.csproj", "{1EE45374-EF8E-4E9D-A74F-51C14DA58ED8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -1356,6 +1372,54 @@ Global {C265268A-F311-4B6A-915E-C1AF9D1EB624}.Release|Any CPU.Build.0 = Release|Any CPU {C265268A-F311-4B6A-915E-C1AF9D1EB624}.Release|x64.ActiveCfg = Release|Any CPU {C265268A-F311-4B6A-915E-C1AF9D1EB624}.Release|x64.Build.0 = Release|Any CPU + {ABF6E41A-CBF9-49DE-87FC-9D88F440A104}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ABF6E41A-CBF9-49DE-87FC-9D88F440A104}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ABF6E41A-CBF9-49DE-87FC-9D88F440A104}.Debug|x64.ActiveCfg = Debug|Any CPU + {ABF6E41A-CBF9-49DE-87FC-9D88F440A104}.Debug|x64.Build.0 = Debug|Any CPU + {ABF6E41A-CBF9-49DE-87FC-9D88F440A104}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ABF6E41A-CBF9-49DE-87FC-9D88F440A104}.Release|Any CPU.Build.0 = Release|Any CPU + {ABF6E41A-CBF9-49DE-87FC-9D88F440A104}.Release|x64.ActiveCfg = Release|Any CPU + {ABF6E41A-CBF9-49DE-87FC-9D88F440A104}.Release|x64.Build.0 = Release|Any CPU + {1CDA9001-A29F-4EBE-BBEA-0B2E663B9A19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1CDA9001-A29F-4EBE-BBEA-0B2E663B9A19}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1CDA9001-A29F-4EBE-BBEA-0B2E663B9A19}.Debug|x64.ActiveCfg = Debug|Any CPU + {1CDA9001-A29F-4EBE-BBEA-0B2E663B9A19}.Debug|x64.Build.0 = Debug|Any CPU + {1CDA9001-A29F-4EBE-BBEA-0B2E663B9A19}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1CDA9001-A29F-4EBE-BBEA-0B2E663B9A19}.Release|Any CPU.Build.0 = Release|Any CPU + {1CDA9001-A29F-4EBE-BBEA-0B2E663B9A19}.Release|x64.ActiveCfg = Release|Any CPU + {1CDA9001-A29F-4EBE-BBEA-0B2E663B9A19}.Release|x64.Build.0 = Release|Any CPU + {00659C82-2E23-4E8F-BA34-EC41D78C87A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {00659C82-2E23-4E8F-BA34-EC41D78C87A1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {00659C82-2E23-4E8F-BA34-EC41D78C87A1}.Debug|x64.ActiveCfg = Debug|Any CPU + {00659C82-2E23-4E8F-BA34-EC41D78C87A1}.Debug|x64.Build.0 = Debug|Any CPU + {00659C82-2E23-4E8F-BA34-EC41D78C87A1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {00659C82-2E23-4E8F-BA34-EC41D78C87A1}.Release|Any CPU.Build.0 = Release|Any CPU + {00659C82-2E23-4E8F-BA34-EC41D78C87A1}.Release|x64.ActiveCfg = Release|Any CPU + {00659C82-2E23-4E8F-BA34-EC41D78C87A1}.Release|x64.Build.0 = Release|Any CPU + {28893415-0789-4FBB-A8B7-F0F9260CEDE3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28893415-0789-4FBB-A8B7-F0F9260CEDE3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28893415-0789-4FBB-A8B7-F0F9260CEDE3}.Debug|x64.ActiveCfg = Debug|Any CPU + {28893415-0789-4FBB-A8B7-F0F9260CEDE3}.Debug|x64.Build.0 = Debug|Any CPU + {28893415-0789-4FBB-A8B7-F0F9260CEDE3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28893415-0789-4FBB-A8B7-F0F9260CEDE3}.Release|Any CPU.Build.0 = Release|Any CPU + {28893415-0789-4FBB-A8B7-F0F9260CEDE3}.Release|x64.ActiveCfg = Release|Any CPU + {28893415-0789-4FBB-A8B7-F0F9260CEDE3}.Release|x64.Build.0 = Release|Any CPU + {D855894E-4C72-41DC-8F84-EF66CDE37453}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D855894E-4C72-41DC-8F84-EF66CDE37453}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D855894E-4C72-41DC-8F84-EF66CDE37453}.Debug|x64.ActiveCfg = Debug|Any CPU + {D855894E-4C72-41DC-8F84-EF66CDE37453}.Debug|x64.Build.0 = Debug|Any CPU + {D855894E-4C72-41DC-8F84-EF66CDE37453}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D855894E-4C72-41DC-8F84-EF66CDE37453}.Release|Any CPU.Build.0 = Release|Any CPU + {D855894E-4C72-41DC-8F84-EF66CDE37453}.Release|x64.ActiveCfg = Release|Any CPU + {D855894E-4C72-41DC-8F84-EF66CDE37453}.Release|x64.Build.0 = Release|Any CPU + {1EE45374-EF8E-4E9D-A74F-51C14DA58ED8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1EE45374-EF8E-4E9D-A74F-51C14DA58ED8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1EE45374-EF8E-4E9D-A74F-51C14DA58ED8}.Debug|x64.ActiveCfg = Debug|Any CPU + {1EE45374-EF8E-4E9D-A74F-51C14DA58ED8}.Debug|x64.Build.0 = Debug|Any CPU + {1EE45374-EF8E-4E9D-A74F-51C14DA58ED8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1EE45374-EF8E-4E9D-A74F-51C14DA58ED8}.Release|Any CPU.Build.0 = Release|Any CPU + {1EE45374-EF8E-4E9D-A74F-51C14DA58ED8}.Release|x64.ActiveCfg = Release|Any CPU + {1EE45374-EF8E-4E9D-A74F-51C14DA58ED8}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1400,7 +1464,6 @@ Global {428CDAF3-957A-4017-82EA-70737F205546} = {38E6C400-90C0-493E-9266-C1602E229F1B} {DB93B639-899D-4B2C-AF8A-47B4BC6B3776} = {9EEE31DA-3165-4CB3-AAE9-27CC3A4DE669} {9EEE31DA-3165-4CB3-AAE9-27CC3A4DE669} = {38E6C400-90C0-493E-9266-C1602E229F1B} - {A5C1EF6B-A3B5-4D0C-8373-F854EE7EF4AD} = {38E6C400-90C0-493E-9266-C1602E229F1B} {B29ABF5D-AFA8-4480-B74E-3ACB6FAAA826} = {13EDB361-AF88-4F89-B4AB-46622BCCBC37} {5A163042-B03A-4063-85FF-22D4C5BB5B90} = {38E6C400-90C0-493E-9266-C1602E229F1B} {84EFF9E1-6852-458F-8D57-62E3F084EA0F} = {9EEE31DA-3165-4CB3-AAE9-27CC3A4DE669} @@ -1517,6 +1580,15 @@ Global {4CD3D849-7277-4C9C-9461-7ABB66F78629} = {38E6C400-90C0-493E-9266-C1602E229F1B} {FED315CF-7CA2-4653-AD37-BC0C1D7FFD22} = {38E6C400-90C0-493E-9266-C1602E229F1B} {C265268A-F311-4B6A-915E-C1AF9D1EB624} = {0D34A7F0-DC77-4789-A136-93089CBD15C3} + {ABF6E41A-CBF9-49DE-87FC-9D88F440A104} = {DC578D74-98F0-4F19-A230-CFA8DAEE0AF1} + {F9DDEB6F-25F8-4505-8300-2E247564BD8B} = {593A3114-D1E0-47ED-BC37-58E08886175B} + {1CDA9001-A29F-4EBE-BBEA-0B2E663B9A19} = {F9DDEB6F-25F8-4505-8300-2E247564BD8B} + {00659C82-2E23-4E8F-BA34-EC41D78C87A1} = {F9DDEB6F-25F8-4505-8300-2E247564BD8B} + {28893415-0789-4FBB-A8B7-F0F9260CEDE3} = {F9DDEB6F-25F8-4505-8300-2E247564BD8B} + {4AA6B450-D4AA-4474-9ECF-52A44935D8D9} = {38E6C400-90C0-493E-9266-C1602E229F1B} + {A5C1EF6B-A3B5-4D0C-8373-F854EE7EF4AD} = {4AA6B450-D4AA-4474-9ECF-52A44935D8D9} + {D855894E-4C72-41DC-8F84-EF66CDE37453} = {4AA6B450-D4AA-4474-9ECF-52A44935D8D9} + {1EE45374-EF8E-4E9D-A74F-51C14DA58ED8} = {4AA6B450-D4AA-4474-9ECF-52A44935D8D9} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {40383055-CC50-4600-AD9A-53C14F620D03} diff --git a/src/BuildingBlocks/MASA.BuildingBlocks b/src/BuildingBlocks/MASA.BuildingBlocks index 6bb92bb70..aac974647 160000 --- a/src/BuildingBlocks/MASA.BuildingBlocks +++ b/src/BuildingBlocks/MASA.BuildingBlocks @@ -1 +1 @@ -Subproject commit 6bb92bb70d76b38d5ef1a1315d035c2567051aad +Subproject commit aac9746472bbdf191f7cb2918dabd6f08cd561bc diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/CallerOptionsExtensions.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/CallerOptionsExtensions.cs new file mode 100644 index 000000000..783ffc0bb --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/CallerOptionsExtensions.cs @@ -0,0 +1,40 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.DaprClient; + +public static class CallerOptionsExtensions +{ + public static CallerOptions UseDapr(this CallerOptions callerOptions, Func clientBuilder) + { + if (clientBuilder == null) + throw new ArgumentNullException(nameof(clientBuilder)); + + MasaDaprClientBuilder builder = clientBuilder.Invoke(); + if (clientBuilder == null) + throw new ArgumentNullException(nameof(clientBuilder)); + + callerOptions.Services.AddDaprClient(daprClientBuilder => + { + if (callerOptions.JsonSerializerOptions != null) + daprClientBuilder.UseJsonSerializationOptions(callerOptions.JsonSerializerOptions); + + builder.Configure?.Invoke(daprClientBuilder); + }); + + AddCallerExtensions.AddCaller(callerOptions, builder.Name, builder.IsDefault, + serviceProvider => new DaprCallerProvider(serviceProvider, builder.Name, builder.AppId)); + return callerOptions; + } + + public static CallerOptions UseDapr(this CallerOptions callerOptions, Action clientBuilder) + { + if (clientBuilder == null) + throw new ArgumentNullException(nameof(clientBuilder)); + + MasaDaprClientBuilder builder = new MasaDaprClientBuilder(); + clientBuilder.Invoke(builder); + + return callerOptions.UseDapr(() => builder); + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCallerBase.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCallerBase.cs new file mode 100644 index 000000000..5c271fb4d --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCallerBase.cs @@ -0,0 +1,31 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.DaprClient; + +public abstract class DaprCallerBase : CallerBase +{ + protected abstract string AppId { get; set; } + + public virtual Action? Configure { get; set; } = null; + + protected DaprCallerBase(IServiceProvider serviceProvider) : base(serviceProvider) + { + } + + public override void UseCallerExtension() => UseDapr(); + + protected virtual DefaultDaprClientBuilder UseDapr() + { + CallerOptions.UseDapr(opt => + { + opt.Name = Name; + opt.AppId = AppId; + if (Configure != null) + { + opt.Configure = Configure; + } + }); + return new DefaultDaprClientBuilder(CallerOptions.Services, Name); + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCallerProvider.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCallerProvider.cs new file mode 100644 index 000000000..ac8f35e23 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCallerProvider.cs @@ -0,0 +1,91 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.DaprClient; + +public class DaprCallerProvider : AbstractCallerProvider +{ + private Dapr.Client.DaprClient? _daprClient; + private Dapr.Client.DaprClient DaprClient => _daprClient ??= ServiceProvider.GetRequiredService(); + private readonly CallerDaprClientOptions _callerDaprClientOptions; + protected readonly string AppId; + + public DaprCallerProvider(IServiceProvider serviceProvider, string name, string appId) + : base(serviceProvider) + { + var optionsFactory = serviceProvider.GetRequiredService>(); + _callerDaprClientOptions = optionsFactory.Create(name); + AppId = appId; + } + + public override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken = default) + where TResponse : default + { + var response = await DaprClient.InvokeMethodWithResponseAsync(request, cancellationToken); + return await ResponseMessage.ProcessResponseAsync(response, cancellationToken); + } + + public override async Task CreateRequestAsync(HttpMethod method, string? methodName) + { + var httpRequestMessage = + await RequestMessage.ProcessHttpRequestMessageAsync(DaprClient.CreateInvokeMethodRequest(method, AppId, methodName)); + + DealRequestMessage(Action); + + return httpRequestMessage; + + async void Action(IDaprRequestMessage requestMessage) + { + await requestMessage.ProcessHttpRequestMessageAsync(httpRequestMessage); + } + } + + public override async Task CreateRequestAsync(HttpMethod method, string? methodName, TRequest data) + { + var httpRequestMessage = + await RequestMessage.ProcessHttpRequestMessageAsync(DaprClient.CreateInvokeMethodRequest(method, AppId, methodName), data); + + DealRequestMessage(Action); + + return httpRequestMessage; + + async void Action(IDaprRequestMessage requestMessage) + { + await requestMessage.ProcessHttpRequestMessageAsync(httpRequestMessage); + } + } + + private void DealRequestMessage(Action action) + { + foreach (var httpRequestMessageAction in _callerDaprClientOptions.HttpRequestMessageActions) + { + MasaHttpMessageHandlerBuilder masaHttpMessageHandlerBuilder = new MasaHttpMessageHandlerBuilder(ServiceProvider); + httpRequestMessageAction.Invoke(masaHttpMessageHandlerBuilder); + + foreach (var requestMessage in masaHttpMessageHandlerBuilder.RequestMessages) + { + action.Invoke(requestMessage); + } + } + } + + public override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken = default) + { + return await DaprClient.InvokeMethodWithResponseAsync(request, cancellationToken); + } + + public override Task SendGrpcAsync(string methodName, CancellationToken cancellationToken = default) + => DaprClient.InvokeMethodGrpcAsync(AppId, methodName, cancellationToken); + + public override Task SendGrpcAsync(string methodName, CancellationToken cancellationToken = default) + => DaprClient.InvokeMethodGrpcAsync(AppId, methodName, cancellationToken); + + public override Task SendGrpcAsync(string methodName, TRequest request, CancellationToken cancellationToken = default) + => DaprClient.InvokeMethodGrpcAsync(AppId, methodName, request, cancellationToken); + + public override Task SendGrpcAsync( + string methodName, + TRequest request, + CancellationToken cancellationToken = default) + => DaprClient.InvokeMethodGrpcAsync(AppId, methodName, cancellationToken); +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DefaultDaprClientBuilder.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DefaultDaprClientBuilder.cs new file mode 100644 index 000000000..562cd81af --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DefaultDaprClientBuilder.cs @@ -0,0 +1,17 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.DaprClient; + +public class DefaultDaprClientBuilder +{ + public IServiceCollection Services { get; private set; } + + public string Name { get; private set; } + + public DefaultDaprClientBuilder(IServiceCollection services, string name) + { + Services = services; + Name = name; + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/HttpMessageHandlerBuilder.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/HttpMessageHandlerBuilder.cs new file mode 100644 index 000000000..6f49049ad --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/HttpMessageHandlerBuilder.cs @@ -0,0 +1,14 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.DaprClient; + +public class MasaHttpMessageHandlerBuilder +{ + public IList RequestMessages { get; } = new List(); + + public virtual IServiceProvider ServiceProvider { get; } + + public MasaHttpMessageHandlerBuilder(IServiceProvider serviceProvider) + => ServiceProvider = serviceProvider; +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/IDaprRequestMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/IDaprRequestMessage.cs new file mode 100644 index 000000000..2ebec9009 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/IDaprRequestMessage.cs @@ -0,0 +1,9 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.DaprClient; + +public interface IDaprRequestMessage +{ + Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage); +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/Masa.Contrib.Service.Caller.DaprClient.csproj b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/Masa.Contrib.Service.Caller.DaprClient.csproj new file mode 100644 index 000000000..4095df268 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/Masa.Contrib.Service.Caller.DaprClient.csproj @@ -0,0 +1,17 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/MasaDaprClientBuilder.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/MasaDaprClientBuilder.cs new file mode 100644 index 000000000..e06b48a26 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/MasaDaprClientBuilder.cs @@ -0,0 +1,70 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.DaprClient; + +public class MasaDaprClientBuilder +{ + private string _appId = default!; + + public string AppId + { + get + { + return _appId; + } + set + { + if (string.IsNullOrEmpty(value)) + throw new ArgumentNullException(nameof(AppId)); + + _appId = value; + } + } + + private string _name = default!; + + public string Name + { + get + { + return _name; + } + set + { + if (value is null) + throw new ArgumentNullException(nameof(Name)); + + _name = value; + } + } + + public bool IsDefault { get; set; } = false; + + public Action? Configure { get; set; } + + internal MasaDaprClientBuilder() + { + this.Name = string.Empty; + } + + public MasaDaprClientBuilder(string appid) + : this(appid, "dapr") { } + + public MasaDaprClientBuilder(string appid, string name) + : this(appid, name, null) + { + } + + public MasaDaprClientBuilder(string appid, string name, Action? configure) : this(appid, name, configure, false) + { + } + + public MasaDaprClientBuilder(string appid, string name, Action? configure, bool isDefault) + { + AppId = appid; + Name = name; + Configure = configure; + IsDefault = isDefault; + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/MasaDaprClientBuilderExtensions.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/MasaDaprClientBuilderExtensions.cs new file mode 100644 index 000000000..ad91b3a03 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/MasaDaprClientBuilderExtensions.cs @@ -0,0 +1,48 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.DaprClient; + +public static class MasaDaprClientBuilderExtensions +{ + public static DefaultDaprClientBuilder AddHttpRequestMessage( + this DefaultDaprClientBuilder builder) + where TRequestMessage : class, IDaprRequestMessage + { + ArgumentNullException.ThrowIfNull(builder); + + builder.Services.TryAddEnumerable(new ServiceDescriptor( + typeof(IDaprRequestMessage), + typeof(TRequestMessage), + ServiceLifetime.Singleton)); + + builder.Services.Configure(builder.Name, option => + { + option.HttpRequestMessageActions.Add(b + => b.RequestMessages.Add( + b.ServiceProvider + .GetServices() + .FirstOrDefault(d => d.GetType() == typeof(TRequestMessage))!)); + }); + return builder; + } + + public static IHttpClientBuilder AddHttpRequestMessage( + this IHttpClientBuilder builder, + Func configureHandler) + where TRequestMessage : class, IDaprRequestMessage + { + ArgumentNullException.ThrowIfNull(nameof(builder)); + + ArgumentNullException.ThrowIfNull(configureHandler); + + builder.Services.TryAddEnumerable(new ServiceDescriptor(typeof(IDaprRequestMessage), configureHandler, ServiceLifetime.Singleton)); + + builder.Services.Configure(builder.Name, options => + { + options.HttpRequestMessageActions.Add(b => b.RequestMessages.Add(configureHandler.Invoke(b.ServiceProvider))); + }); + + return builder; + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/Options/CallerDaprClientOptions.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/Options/CallerDaprClientOptions.cs new file mode 100644 index 000000000..a8c890bbb --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/Options/CallerDaprClientOptions.cs @@ -0,0 +1,9 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.DaprClient.Options; + +public class CallerDaprClientOptions +{ + public IList> HttpRequestMessageActions { get; } = new List>(); +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.md b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.md new file mode 100644 index 000000000..76b92be37 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.md @@ -0,0 +1,101 @@ +[中](README.zh-CN.md) | EN + +## Masa.Contrib.Service.Caller.DaprClient + +## Example: + +````c# +Install-Package Masa.Contrib.Service.Caller.DaprClient +```` + +### Basic usage: + +1. Modify `Program.cs` + + ```` C# + builder.Services.AddCaller(options => + { + options.UseDapr(clientBuilder => + { + clientBuilder.Name = "UserCaller";// The alias of the current Caller, when there is only one Provider, you can not assign a value to Name + clientBuilder.AppId = "" ;//AppID of the callee dapr + }); + }); + ```` + +2. How to use: + + ```` C# + app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) + => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + ```` + + > The interface address of the complete request is: http://localhost:3500/v1.0/invoke//method/Hello?Name={name} + +3. When there are multiple DaprClients, modify `Program.cs` + + ```` C# + builder.Services.AddCaller(options => + { + options.UseDapr(clientBuilder => + { + clientBuilder.Name = "UserCaller"; + clientBuilder.AppId = "" ;//AppID of the callee User service Dapr + }); + options.UseDapr(clientBuilder => + { + clientBuilder.Name = "OrderCaller"; + clientBuilder.AppId = "" ;//AppID of the callee Order service Dapr + }); + }); + ```` + +4. How to use UserCaller or OrderCaller + + ```` C# + app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) + => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + + + app.MapGet("/Test/Order/Hello", ([FromServices] ICallerFactory callerFactory, string name) => + { + var callerProvider = callerFactory.CreateClient("OrderCaller"); + return callerProvider.GetAsync($"/Hello", new { Name = name }); + }); + ```` + +> When multiple Callers are added, how to get the specified Caller? +>> Get the CallerProvider of the specified alias through the `CreateClient` method of `CallerFactory` +> +> Why doesn't `userCallerProvider` get the corresponding Caller through the `CreateClient` method of `CallerFactory`? +>> If no default ICallerProvider is specified, the default CallerProvider is the first one added in the `AddCaller` method + +### Recommended usage + +1. Modify `Program.cs` + + ```` C# + builder.Services.AddCaller(); + ```` + +2. Add a new class `UserCaller` + + ```` C# + public class UserCaller: DaprCallerBase + { + protected override string AppId { get; set; } = ""; + + public HttpCaller(IServiceProvider serviceProvider) : base(serviceProvider) + { + } + + public Task HelloAsync(string name) => CallerProvider.GetStringAsync($"/Hello", new { Name = name }); + } + ```` + +3. How to use UserCaller + + ```` C# + app.MapGet("/Test/User/Hello", ([FromServices] UserCaller caller, string name) + => caller.HelloAsync(name)); + ```` \ No newline at end of file diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md new file mode 100644 index 000000000..242b3e93c --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md @@ -0,0 +1,101 @@ +中 | [EN](README.md) + +## Masa.Contrib.Service.Caller.DaprClient + +## 用例: + +```c# +Install-Package Masa.Contrib.Service.Caller.DaprClient +``` + +### 基本用法: + +1. 修改`Program.cs` + + ``` C# + builder.Services.AddCaller(options => + { + options.UseDapr(clientBuilder => + { + clientBuilder.Name = "UserCaller";// 当前Caller的别名,仅存在一个Provider时,可以不对Name赋值 + clientBuilder.AppId = "" ;//被调用方dapr的AppID + }); + }); + ``` + +2. 如何使用: + + ``` C# + app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) + => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + ``` + + > 完整请求的接口地址是:http://localhost:3500/v1.0/invoke//method/Hello?Name={name} + +3. 当存在多个DaprClient时,则修改`Program.cs`为 + + ``` C# + builder.Services.AddCaller(options => + { + options.UseDapr(clientBuilder => + { + clientBuilder.Name = "UserCaller"; + clientBuilder.AppId = "" ;//被调用方User服务Dapr的AppID + }); + options.UseDapr(clientBuilder => + { + clientBuilder.Name = "OrderCaller"; + clientBuilder.AppId = "" ;//被调用方Order服务Dapr的AppID + }); + }); + ``` + +4. 如何使用UserCaller或OrderCaller + + ``` C# + app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) + => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + + + app.MapGet("/Test/Order/Hello", ([FromServices] ICallerFactory callerFactory, string name) => + { + var callerProvider = callerFactory.CreateClient("OrderCaller"); + return callerProvider.GetAsync($"/Hello", new { Name = name }); + }); + ``` + +> 当多个Caller被添加时,如何获取指定的Caller? +>> 通过`CallerFactory`的`CreateClient`方法得到指定别名的CallerProvider +> +> 为什么`userCallerProvider`没有通过`CallerFactory`的`CreateClient`方法得到对应的Caller? +>> 如果未指定默认的ICallerProvider,则在`AddCaller`方法中第一个被添加的就是默认的CallerProvider + +### 推荐用法 + +1. 修改`Program.cs` + + ``` C# + builder.Services.AddCaller(); + ``` + +2. 新增加类`UserCaller` + + ``` C# + public class UserCaller: DaprCallerBase + { + protected override string AppId { get; set; } = ""; + + public HttpCaller(IServiceProvider serviceProvider) : base(serviceProvider) + { + } + + public Task HelloAsync(string name) => CallerProvider.GetStringAsync($"/Hello", new { Name = name }); + } + ``` + +3. 如何使用UserCaller + + ``` C# + app.MapGet("/Test/User/Hello", ([FromServices] UserCaller caller, string name) + => caller.HelloAsync(name)); + ``` \ No newline at end of file diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/_Imports.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/_Imports.cs new file mode 100644 index 000000000..37d02e325 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/_Imports.cs @@ -0,0 +1,10 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +global using Dapr.Client; +global using Masa.BuildingBlocks.Service.Caller; +global using Masa.BuildingBlocks.Service.Caller.Options; +global using Masa.Contrib.Service.Caller.DaprClient.Options; +global using Microsoft.Extensions.DependencyInjection; +global using Microsoft.Extensions.DependencyInjection.Extensions; +global using Microsoft.Extensions.Options; diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/CallerOptionsExtensions.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/CallerOptionsExtensions.cs new file mode 100644 index 000000000..bf31e1ebf --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/CallerOptionsExtensions.cs @@ -0,0 +1,26 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.HttpClient; + +public static class CallerOptionsExtensions +{ + public static IHttpClientBuilder UseHttpClient(this CallerOptions callerOptions, Func? clientBuilder = null) + { + var builder = clientBuilder == null ? new MasaHttpClientBuilder() : clientBuilder.Invoke(); + var httpClientBuilder = callerOptions.Services.AddHttpClient(builder.Name, httpClient + => builder.ConfigureHttpClient(httpClient)); + + AddCallerExtensions.AddCaller(callerOptions, builder.Name, builder.IsDefault, serviceProvider + => new HttpClientCallerProvider(serviceProvider, builder.Name, builder.Prefix)); + return httpClientBuilder; + } + + public static IHttpClientBuilder UseHttpClient(this CallerOptions callerOptions, Action? clientBuilder) + { + MasaHttpClientBuilder builder = new MasaHttpClientBuilder(); + clientBuilder?.Invoke(builder); + + return callerOptions.UseHttpClient(() => builder); + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCallerBase.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCallerBase.cs new file mode 100644 index 000000000..efec26b02 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCallerBase.cs @@ -0,0 +1,32 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.HttpClient; + +public abstract class HttpClientCallerBase : CallerBase +{ + protected abstract string BaseAddress { get; set; } + + protected virtual string Prefix { get; set; } = string.Empty; + + protected HttpClientCallerBase(IServiceProvider serviceProvider) : base(serviceProvider) + { + } + + public override void UseCallerExtension() => UseHttpClient(); + + protected virtual IHttpClientBuilder UseHttpClient() + { + return CallerOptions.UseHttpClient(httpClientBuilder => + { + httpClientBuilder.Name = Name; + httpClientBuilder.Prefix = Prefix; + httpClientBuilder.BaseAddress = BaseAddress; + httpClientBuilder.Configure = ConfigureHttpClient; + }); + } + + protected virtual void ConfigureHttpClient(System.Net.Http.HttpClient httpClient) + { + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCallerProvider.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCallerProvider.cs new file mode 100644 index 000000000..4a7647b7a --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCallerProvider.cs @@ -0,0 +1,72 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.HttpClient; + +public class HttpClientCallerProvider : AbstractCallerProvider +{ + private readonly System.Net.Http.HttpClient _httpClient; + private readonly string _prefix; + private readonly bool _prefixIsNullOrEmpty; + + public HttpClientCallerProvider(IServiceProvider serviceProvider, string name, string prefix) + : base(serviceProvider) + { + _httpClient = serviceProvider.GetRequiredService().CreateClient(name); + _prefix = prefix; + _prefixIsNullOrEmpty = string.IsNullOrEmpty(_prefix); + } + + public override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken = default) + where TResponse : default + { + var response = await _httpClient.SendAsync(request, cancellationToken); + return await ResponseMessage.ProcessResponseAsync(response, cancellationToken); + } + + public override Task CreateRequestAsync(HttpMethod method, string? methodName) + => RequestMessage.ProcessHttpRequestMessageAsync(new HttpRequestMessage(method, GetRequestUri(methodName))); + + public override Task CreateRequestAsync(HttpMethod method, string? methodName, TRequest data) + => RequestMessage.ProcessHttpRequestMessageAsync(new HttpRequestMessage(method, GetRequestUri(methodName)), data); + + public override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken = default) + { + return _httpClient.SendAsync(request, cancellationToken); + } + + public override Task SendGrpcAsync(string methodName, CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + public override Task SendGrpcAsync(string methodName, CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + public override Task SendGrpcAsync(string methodName, TRequest request, CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + public override Task SendGrpcAsync(string methodName, TRequest request, + CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + protected virtual string GetRequestUri(string? methodName) + { + if (string.IsNullOrEmpty(methodName)) + return string.Empty; + + if (Uri.IsWellFormedUriString(methodName, UriKind.Absolute) || _prefixIsNullOrEmpty) + return methodName; + + if (_prefix.EndsWith("/")) + return $"{_prefix}{(methodName.StartsWith("/") ? methodName.Substring(1) : methodName)}"; + + return $"{_prefix}{(methodName.StartsWith("/") ? methodName : "/" + methodName)}"; + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/Masa.Contrib.Service.Caller.HttpClient.csproj b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/Masa.Contrib.Service.Caller.HttpClient.csproj new file mode 100644 index 000000000..83d386c93 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/Masa.Contrib.Service.Caller.HttpClient.csproj @@ -0,0 +1,17 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/MasaHttpClientBuilder.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/MasaHttpClientBuilder.cs new file mode 100644 index 000000000..516d483c2 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/MasaHttpClientBuilder.cs @@ -0,0 +1,62 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.HttpClient; + +public class MasaHttpClientBuilder +{ + private string _name = default!; + + public string Name + { + get => _name; + set + { + if (value is null) + throw new ArgumentNullException(Name); + + _name = value; + } + } + + [Obsolete($"recommended to use {nameof(BaseAddress)}, {nameof(BaseApi)} has expired")] + public string BaseApi { get => BaseAddress; set => BaseAddress = value; } + + public string BaseAddress { get; set; } + + public string Prefix { get; set; } + + public bool IsDefault { get; set; } = false; + + public Action? Configure { get; set; } + + public MasaHttpClientBuilder() : this("http", null) + { + } + + public MasaHttpClientBuilder(string name, Action? configure) + : this(name, string.Empty, configure) + { + } + + public MasaHttpClientBuilder(string name, string baseAddress, Action? configure) + : this(name, baseAddress, string.Empty, configure) + { + } + + public MasaHttpClientBuilder(string name, string baseAddress, string prefix, Action? configure) + { + Name = name; + BaseAddress = baseAddress; + Prefix = prefix; + Configure = configure; + } + + public virtual void ConfigureHttpClient(System.Net.Http.HttpClient httpClient) + { + if (!string.IsNullOrEmpty(BaseAddress)) + httpClient.BaseAddress = new Uri(BaseAddress); + + Configure?.Invoke(httpClient); + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.md b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.md new file mode 100644 index 000000000..98b9c0b6c --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.md @@ -0,0 +1,110 @@ +[中](README.zh-CN.md) | EN + +## Masa.Contrib.Service.Caller.HttpClient + +## Example: + +````c# +Install-Package Masa.Contrib.Service.Caller.HttpClient +```` + +### Basic usage: + +1. Modify `Program.cs` + + ```` C# + builder.Services.AddCaller(options => + { + options.UseHttpClient(httpClientBuilder => + { + httpClientBuilder.Name = "UserCaller";// The alias of the current Caller, when there is only one HttpClient, you can not assign a value to Name + httpClientBuilder.BaseAddress = "http://localhost:5000" ; + }); + }); + ```` + +2. How to use: + + ```` C# + app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) + => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + ```` + + > The interface address of the complete request is: http://localhost:5000/Hello?Name={name} + +3. When there are multiple HttpClients, modify `Program.cs` + + ```` C# + builder.Services.AddCaller(options => + { + options.UseHttpClient(httpClientBuilder => + { + httpClientBuilder.Name = "UserCaller"; + httpClientBuilder.BaseAddress = "http://localhost:5000" ; + }); + options.UseHttpClient(httpClientBuilder => + { + httpClientBuilder.Name = "OrderCaller"; + httpClientBuilder.BaseAddress = "http://localhost:6000" ; + }); + }); + ```` + +4. How to use UserCaller or OrderCaller + + ```` C# + app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) + => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + + + app.MapGet("/Test/Order/Hello", ([FromServices] ICallerFactory callerFactory, string name) => + { + var callerProvider = callerFactory.CreateClient("OrderCaller"); + return callerProvider.GetAsync($"/Hello", new { Name = name }); + }); + ```` + +> When multiple Callers are added, how to get the specified Caller? +>> Get the CallerProvider of the specified alias through the `CreateClient` method of `CallerFactory` +> +> Why doesn't `userCallerProvider` get the corresponding Caller through the `CreateClient` method of `CallerFactory`? +>> If no default ICallerProvider is specified, the default CallerProvider is the first one added in the `AddCaller` method + +### Recommended usage + +1. Modify `Program.cs` + + ```` C# + builder.Services.AddCaller(); + ```` + +2. Add a new class `UserCaller` + + ```` C# + public class UserCaller: HttpClientCallerBase + { + protected override string BaseAddress { get; set; } = "http://localhost:5000"; + + public HttpCaller(IServiceProvider serviceProvider) : base(serviceProvider) + { + } + + public Task HelloAsync(string name) => CallerProvider.GetStringAsync($"/Hello", new { Name = name }); + + /// + /// There is no need to overload by default, and it can be overloaded when there are special requirements for httpClient + /// + /// + protected override void ConfigureHttpClient(System.Net.Http.HttpClient httpClient) + { + httpClient.Timeout = TimeSpan.FromSeconds(5); + } + } + ```` + +3. How to use UserCaller + + ```` C# + app.MapGet("/Test/User/Hello", ([FromServices] UserCaller caller, string name) + => caller.HelloAsync(name)); + ```` \ No newline at end of file diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md new file mode 100644 index 000000000..9b978b6cb --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md @@ -0,0 +1,110 @@ +中 | [EN](README.md) + +## Masa.Contrib.Service.Caller.HttpClient + +## 用例: + +```c# +Install-Package Masa.Contrib.Service.Caller.HttpClient +``` + +### 基本用法: + +1. 修改`Program.cs` + + ``` C# + builder.Services.AddCaller(options => + { + options.UseHttpClient(httpClientBuilder => + { + httpClientBuilder.Name = "UserCaller";// 当前Caller的别名,仅存在一个HttpClient时,可以不对Name赋值 + httpClientBuilder.BaseAddress = "http://localhost:5000" ; + }); + }); + ``` + +2. 如何使用: + + ``` C# + app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) + => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + ``` + + > 完整请求的接口地址是:http://localhost:5000/Hello?Name={name} + +3. 当存在多个HttpClient时,则修改`Program.cs`为 + + ``` C# + builder.Services.AddCaller(options => + { + options.UseHttpClient(httpClientBuilder => + { + httpClientBuilder.Name = "UserCaller"; + httpClientBuilder.BaseAddress = "http://localhost:5000" ; + }); + options.UseHttpClient(httpClientBuilder => + { + httpClientBuilder.Name = "OrderCaller"; + httpClientBuilder.BaseAddress = "http://localhost:6000" ; + }); + }); + ``` + +4. 如何使用UserCaller或OrderCaller + + ``` C# + app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) + => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + + + app.MapGet("/Test/Order/Hello", ([FromServices] ICallerFactory callerFactory, string name) => + { + var callerProvider = callerFactory.CreateClient("OrderCaller"); + return callerProvider.GetAsync($"/Hello", new { Name = name }); + }); + ``` + +> 当多个Caller被添加时,如何获取指定的Caller? +>> 通过`CallerFactory`的`CreateClient`方法得到指定别名的CallerProvider +> +> 为什么`userCallerProvider`没有通过`CallerFactory`的`CreateClient`方法得到对应的Caller? +>> 如果未指定默认的ICallerProvider,则在`AddCaller`方法中第一个被添加的就是默认的CallerProvider + +### 推荐用法 + +1. 修改`Program.cs` + + ``` C# + builder.Services.AddCaller(); + ``` + +2. 新增加类`UserCaller` + + ``` C# + public class UserCaller: HttpClientCallerBase + { + protected override string BaseAddress { get; set; } = "http://localhost:5000"; + + public HttpCaller(IServiceProvider serviceProvider) : base(serviceProvider) + { + } + + public Task HelloAsync(string name) => CallerProvider.GetStringAsync($"/Hello", new { Name = name }); + + /// + /// 默认不需要重载,对httpClient有特殊需求时可重载 + /// + /// + protected override void ConfigureHttpClient(System.Net.Http.HttpClient httpClient) + { + httpClient.Timeout = TimeSpan.FromSeconds(5); + } + } + ``` + +3. 如何使用UserCaller + + ``` C# + app.MapGet("/Test/User/Hello", ([FromServices] UserCaller caller, string name) + => caller.HelloAsync(name)); + ``` \ No newline at end of file diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/_Imports.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/_Imports.cs new file mode 100644 index 000000000..9710f3e96 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/_Imports.cs @@ -0,0 +1,6 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +global using Masa.BuildingBlocks.Service.Caller; +global using Masa.BuildingBlocks.Service.Caller.Options; +global using Microsoft.Extensions.DependencyInjection; diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultCallerFactory.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultCallerFactory.cs new file mode 100644 index 000000000..ac621343d --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultCallerFactory.cs @@ -0,0 +1,31 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller; + +internal class DefaultCallerFactory : ICallerFactory +{ + private readonly IServiceProvider _serviceProvider; + private readonly List _callers; + + public DefaultCallerFactory(IServiceProvider serviceProvider, IOptionsFactory callerFactoryOptions) + { + _serviceProvider = serviceProvider; + _callers = callerFactoryOptions.Create(Options.DefaultName).Callers; + } + + public ICallerProvider CreateClient() + { + var caller = _callers.SingleOrDefault(c => c.IsDefault) ?? _callers.FirstOrDefault()!; + return caller.Func.Invoke(_serviceProvider); + } + + public ICallerProvider CreateClient(string name) + { + var caller = _callers.SingleOrDefault(c => c.Name == name); + if (caller == null) + throw new NotSupportedException($"Please make sure you have used [{name}] Caller"); + + return caller.Func.Invoke(_serviceProvider); + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestIdGenerator.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestIdGenerator.cs new file mode 100644 index 000000000..0cf6ecc90 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestIdGenerator.cs @@ -0,0 +1,9 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller; + +public class DefaultRequestIdGenerator : IRequestIdGenerator +{ + public string NewId() => Guid.NewGuid().ToString(); +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs new file mode 100644 index 000000000..2b2c9ff33 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs @@ -0,0 +1,35 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller; + +public abstract class DefaultRequestMessage +{ + private readonly string _requestIdKey; + private readonly IRequestIdGenerator _requestIdGenerator; + private readonly IHttpContextAccessor? _httpContextAccessor; + protected readonly CallerFactoryOptions Options; + + public DefaultRequestMessage(IOptionsFactory optionsFactory, + IRequestIdGenerator requestIdGenerator, + IHttpContextAccessor? httpContextAccessor = null) + { + _requestIdGenerator = requestIdGenerator; + _httpContextAccessor = httpContextAccessor; + Options = optionsFactory.Create(Microsoft.Extensions.Options.Options.DefaultName); + _requestIdKey = Options.RequestIdKey ?? "Masa-Request-Id"; + } + + protected void TrySetRequestId(HttpRequestMessage requestMessage) + { + var httpContext = _httpContextAccessor?.HttpContext; + if (httpContext == null) + return; + + if (!httpContext.Request.Headers.TryGetValue(_requestIdKey, out var requestId)) + requestId = _requestIdGenerator.NewId(); + + if (requestMessage.Headers.All(h => h.Key != _requestIdKey)) + requestMessage.Headers.Add(_requestIdKey, requestId.ToString()); + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultResponseMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultResponseMessage.cs new file mode 100644 index 000000000..45b360cc6 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultResponseMessage.cs @@ -0,0 +1,92 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller; + +public class DefaultResponseMessage : IResponseMessage +{ + private readonly ILogger? _logger; + private readonly CallerFactoryOptions _options; + + public DefaultResponseMessage(IOptionsFactory optionsFactory, ILogger? logger = null) + { + _options = optionsFactory.Create(Options.DefaultName); + _logger = logger; + } + + public async Task ProcessResponseAsync(HttpResponseMessage response, + CancellationToken cancellationToken = default) + { + if (response.IsSuccessStatusCode) + { + switch (response.StatusCode) + { + case HttpStatusCode.Accepted: + case HttpStatusCode.NoContent: + return default; + case (HttpStatusCode)MasaHttpStatusCode.UserFriendlyException: + throw new UserFriendlyException(await response.Content.ReadAsStringAsync(cancellationToken)); + default: + if (typeof(TResponse) == typeof(Guid) || typeof(TResponse) == typeof(Guid?)) + { + var content = await response.Content.ReadAsStringAsync(cancellationToken); + if (string.IsNullOrEmpty(content)) + return (TResponse)(object?)null!; + + return (TResponse?)(object)Guid.Parse(content.Replace("\"", "")); + } + if (typeof(TResponse) == typeof(DateTime) || typeof(TResponse) == typeof(DateTime?)) + { + var content = await response.Content.ReadAsStringAsync(cancellationToken); + if (string.IsNullOrEmpty(content)) + return (TResponse)(object?)null!; + + return (TResponse?)(object)DateTime.Parse(content.Replace("\"", "")); + } + if (typeof(TResponse).GetInterfaces().Any(type => type == typeof(IConvertible))) + { + var content = await response.Content.ReadAsStringAsync(cancellationToken); + return (TResponse)Convert.ChangeType(content, typeof(TResponse)); + } + try + { + return await response.Content.ReadFromJsonAsync(_options.JsonSerializerOptions, cancellationToken) + ?? throw new ArgumentException("The response cannot be empty or there is an error in deserialization"); + } + catch (Exception exception) + { + _logger?.LogWarning(exception, exception.Message); + ExceptionDispatchInfo.Capture(exception).Throw(); + return default; //This will never be executed, the previous line has already thrown an exception + } + } + } + + await ProcessResponseExceptionAsync(response, cancellationToken); + return default; //never executed + } + + public async Task ProcessResponseAsync(HttpResponseMessage response, CancellationToken cancellationToken = default) + { + if (response.IsSuccessStatusCode) + { + switch (response.StatusCode) + { + case (HttpStatusCode)MasaHttpStatusCode.UserFriendlyException: + throw new UserFriendlyException(await response.Content.ReadAsStringAsync(cancellationToken)); + default: + return; + } + } + + await ProcessResponseExceptionAsync(response, cancellationToken); + } + + public async Task ProcessResponseExceptionAsync(HttpResponseMessage response, CancellationToken cancellationToken = default) + { + if (response.Content.Headers.ContentLength is > 0) + throw new Exception(await response.Content.ReadAsStringAsync(cancellationToken)); + + throw new MasaException($"ReasonPhrase: {response.ReasonPhrase ?? string.Empty}, StatusCode: {response.StatusCode}"); + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultTypeConvertProvider.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultTypeConvertProvider.cs new file mode 100644 index 000000000..e23dd14f5 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultTypeConvertProvider.cs @@ -0,0 +1,98 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller; + +public class DefaultTypeConvertProvider : ITypeConvertProvider +{ + private static readonly ConcurrentDictionary> Dictionary = new(); + + protected readonly List NotNeedSerializeTypes = new() + { + typeof(String), + typeof(Guid), + typeof(DateTime), + typeof(Decimal), + typeof(Guid?), + typeof(DateTime?), + typeof(Decimal?) + }; + + /// + /// Convert custom object to dictionary + /// + /// + /// Support classes, anonymous objects + /// + [Obsolete("Use ConvertToKeyValuePairs instead")] + public Dictionary ConvertToDictionary(TRequest request) where TRequest : class + => new(ConvertToKeyValuePairs(request)); + + /// + /// Convert custom object to dictionary + /// + /// + /// Support classes, anonymous objects + /// + public IEnumerable> ConvertToKeyValuePairs(TRequest request) where TRequest : class + { + if (request.Equals(null)) + return Array.Empty>(); + + if (request is Dictionary response) + return response; + + if (request is IEnumerable> keyValuePairs) + return keyValuePairs; + + var requestType = request.GetType(); + if (!Dictionary.TryGetValue(requestType, out List? members)) + { + members = GetMembers(request.GetType().GetProperties()); + Dictionary.TryAdd(requestType, members); + } + List> data = new List>(); + foreach (var member in members) + { + if (member.TryGetValue(request, out string value)) + data.Add(new KeyValuePair(member.Name, value)); + } + return data; + } + + private List GetMembers(PropertyInfo[] properties) + { + List members = new(); + foreach (var property in properties) + { + if (IsSkip(property)) continue; + + string name = GetPropertyName(property); + + members.Add(new PropertyInfoMember(property, name, IsNeedSerialize(property))); + } + return members; + } + + protected bool IsSkip(PropertyInfo property) + => !property.CanRead || + !property.PropertyType.IsPublic || + property.CustomAttributes.Any(attr => attr.AttributeType == typeof(JsonIgnoreAttribute)); + + protected string GetPropertyName(PropertyInfo property) + { + if (property.CustomAttributes.Any(attr => attr.AttributeType == typeof(JsonPropertyNameAttribute))) + { + var customAttributeData = + property.CustomAttributes.FirstOrDefault(attr => attr.AttributeType == typeof(JsonPropertyNameAttribute))!; + var customAttribute = customAttributeData.ConstructorArguments.FirstOrDefault(); + return customAttribute.Value?.ToString() ?? + throw new NotSupportedException( + $"Parameter name: {property.Name}, But the JsonPropertyNameAttribute assignment name is empty"); + } + return property.Name; + } + + protected bool IsNeedSerialize(PropertyInfo property) + => !property.PropertyType.IsPrimitive && !NotNeedSerializeTypes.Contains(property.PropertyType); +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/IRequestIdGenerator.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/IRequestIdGenerator.cs new file mode 100644 index 000000000..9f270ee5d --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/IRequestIdGenerator.cs @@ -0,0 +1,9 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller; + +public interface IRequestIdGenerator +{ + string NewId(); +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/Internal/CallerDependExtensions.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/Internal/CallerDependExtensions.cs new file mode 100644 index 000000000..e06d39d2f --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/Internal/CallerDependExtensions.cs @@ -0,0 +1,89 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Internal; + +/// +/// Caller dependency orchestration +/// +internal static class CallerDependExtensions +{ + /// + /// Caller dependency orchestration + /// + /// All Callers that inherit CallerBase + /// + /// + public static List Arrangement(this List callerTypes) + { + List types = GetCallerByNotDependCaller(callerTypes); + if (types.Count == 0) + throw new UserFriendlyException(Const.CIRCULAR_DEPENDENCY); + + return callerTypes.CallersArrangement(types, 1); + } + + private static List CallersArrangement(this List allTypes, List existTypes, int executeTimes) + { + List types = existTypes; + var dependCallerTypes = allTypes.Except(existTypes); + foreach (var type in dependCallerTypes) + { + var constructorInfo = type.GetConstructors().MaxBy(con => con.GetParameters().Length)!; + bool isExist = true; + foreach (var parameter in constructorInfo.GetParameters()) + { + var parameterType = parameter.ParameterType; + if (typeof(CallerBase).IsAssignableFrom(parameterType) && !types.Contains(parameterType)) + { + isExist = false; + } + } + if (isExist) + types.Add(type); + } + + if (types.Count != allTypes.Count) + { + if (executeTimes >= allTypes.Count) + throw new UserFriendlyException(Const.CIRCULAR_DEPENDENCY); + + return CallersArrangement(allTypes, types, ++executeTimes); + } + return types; + } + + /// + /// Get a Caller object that does not depend on other Callers + /// + /// + /// + private static List GetCallerByNotDependCaller(this List callerTypes) + { + List types = new(); + callerTypes.ForEach(type => + { + if (!type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).IsDependCaller()) + types.Add(type); + }); + return types; + } + + private static bool IsDependCaller(this ConstructorInfo[] constructorInfos) + { + var constructorInfo = constructorInfos.MaxBy(constructorInfo => constructorInfo.GetParameters().Length)!; + return constructorInfo.IsDependCaller(); + } + + private static bool IsDependCaller(this ConstructorInfo constructorInfo) + { + foreach (var parameter in constructorInfo.GetParameters()) + { + if (typeof(CallerBase).IsAssignableFrom(parameter.ParameterType)) + { + return true; + } + } + return false; + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/Internal/Const.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/Internal/Const.cs new file mode 100644 index 000000000..ed99488a2 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/Internal/Const.cs @@ -0,0 +1,9 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Internal; + +internal class Const +{ + public const string CIRCULAR_DEPENDENCY = "Caller has a circular dependency, please check the constructor of Caller"; +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/Internal/Options/PropertyInfoMember.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/Internal/Options/PropertyInfoMember.cs new file mode 100644 index 000000000..e7f3ecb7f --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/Internal/Options/PropertyInfoMember.cs @@ -0,0 +1,31 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Internal.Options; + +internal class PropertyInfoMember +{ + public PropertyInfo Property { get; } + + public string Name { get; } + + public bool NeedSerialize { get; } + + public PropertyInfoMember(PropertyInfo property, string name, bool needSerialize) + { + Property = property; + Name = name; + NeedSerialize = needSerialize; + } + + public bool TryGetValue(TRequest data, out string value) where TRequest : class + { + value = string.Empty; + var propertyValue = Property.GetValue(data); + if (propertyValue == null || (!NeedSerialize && propertyValue.ToString() == null)) + return false; + + value = !NeedSerialize ? propertyValue.ToString()! : JsonSerializer.Serialize(propertyValue); + return true; + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs new file mode 100644 index 000000000..cb1e96365 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs @@ -0,0 +1,31 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller; + +public class JsonRequestMessage : DefaultRequestMessage, IRequestMessage +{ + private readonly JsonSerializerOptions? _jsonSerializerOptions; + + public JsonRequestMessage( + IOptionsFactory optionsFactory, + IRequestIdGenerator requestIdGenerator, + IHttpContextAccessor? httpContextAccessor = null) + : base(optionsFactory, requestIdGenerator, httpContextAccessor) + { + _jsonSerializerOptions = Options.JsonSerializerOptions; + } + + public virtual Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage) + { + TrySetRequestId(requestMessage); + return Task.FromResult(requestMessage); + } + + public virtual async Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage, TRequest data) + { + requestMessage = await ProcessHttpRequestMessageAsync(requestMessage); + requestMessage.Content = JsonContent.Create(data, options: _jsonSerializerOptions); + return requestMessage; + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/Masa.Contrib.Service.Caller.csproj b/src/Service/Caller/Masa.Contrib.Service.Caller/Masa.Contrib.Service.Caller.csproj new file mode 100644 index 000000000..24085f18d --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/Masa.Contrib.Service.Caller.csproj @@ -0,0 +1,17 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/README.md b/src/Service/Caller/Masa.Contrib.Service.Caller/README.md new file mode 100644 index 000000000..a5988e2a5 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/README.md @@ -0,0 +1,36 @@ +[中](README.zh-CN.md) | EN + +## Masa.Contrib.Service.Caller + +Masa.Contrib.Service.Caller is the basic class library of Caller, which provides the abstraction of the following capabilities + +* `ICallerFactory`: Factory for creating `CallerProvider` (Singleton) +* `ICallerProvider`: Provides `Post`, `Delete`, `Patch`, `Put`, `Get`, `Send` capabilities (Scoped) +* `IRequestMessage`: Provides the ability to process request data (default implementation [`JsonRequestMessage`](./JsonRequestMessage.cs)) (Singleton) +* `IResponseMessage`: Provides the ability to handle response data (default implementation [`DefaultResponseMessage`](./DefaultResponseMessage.cs)) (Singleton) +* `ITypeConvertProvider`: Provides the ability to convert types, support for `Get` requests of `ICallerProvider` (Singleton) + +## Summarize + +`Masa.Contrib.Service.Caller` is the basic class library of Caller, but it cannot be used alone. Currently, Caller supports two implementations: + +* Implementation based on HttpClient: [Masa.Utils.Caller.HttpClient](../Masa.Utils.Caller.HttpClient/README.md) +* Implementation based on DaprClient: [Masa.Utils.Caller.DaprClient](../Masa.Utils.Caller.DaprClient/README.md) + +> Q: What should I do if the callee uses xml instead of json? +> +> A: Rewrite IRequestMessage and add the custom RequestMessage to the IServiceCollection before calling AddCaller + + ```` C# + services.AddSingleton(); + services.AddCaller(); + ```` + +> Q: If you want to handle custom StatusCode and throw exception information +> +> A: Rewrite IResponseMessage, add custom ResponseMessage to IServiceCollection before calling AddCaller + + ```` C# + services.AddSingleton(); + services.AddCaller(); + ```` \ No newline at end of file diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/README.zh-CN.md b/src/Service/Caller/Masa.Contrib.Service.Caller/README.zh-CN.md new file mode 100644 index 000000000..72c9a4411 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/README.zh-CN.md @@ -0,0 +1,36 @@ +中 | [EN](README.md) + +## Masa.Contrib.Service.Caller + +Masa.Contrib.Service.Caller是Caller的基础类库,提供了以下能力的抽象 + +* `ICallerFactory`: 工厂,用于创建`CallerProvider` (Singleton) +* `ICallerProvider`: 提供`Post`、`Delete`、`Patch`、`Put`、`Get`、`Send`的能力 (Scoped) +* `IRequestMessage`: 提供对请求数据处理的能力 (默认实现[`JsonRequestMessage`](./JsonRequestMessage.cs)) (Singleton) +* `IResponseMessage`: 提供对响应数据处理的能力 (默认实现[`DefaultResponseMessage`](./DefaultResponseMessage.cs)) (Singleton) +* `ITypeConvertProvider`: 提供类型转换的能力,为`ICallerProvider`的`Get`请求支撑 (Singleton) + +## 总结 + +`Masa.Contrib.Service.Caller`是Caller的基础类库,但不能单独使用,目前Caller支持了两种实现方式: + +* 基于HttpClient的实现: [Masa.Utils.Caller.HttpClient](../Masa.Utils.Caller.HttpClient/README.zh-CN.md) +* 基于DaprClient的实现: [Masa.Utils.Caller.DaprClient](../Masa.Utils.Caller.DaprClient/README.zh-CN.md) + +> Q: 如果被调用方使用的是数据格式为xml,而不是json,我应该怎么做? +> +> A: 重写IRequestMessage,在调用AddCaller之前先将自定义的RequestMessage添加到IServiceCollection中 + + ``` C# + services.AddSingleton(); + services.AddCaller(); + ``` + +> Q: 如果希望处理自定义的StatusCode,并抛出异常信息 +> +> A: 重写IResponseMessage,在调用AddCaller之前先将自定义的ResponseMessage添加到IServiceCollection中 + + ``` C# + services.AddSingleton(); + services.AddCaller(); + ``` \ No newline at end of file diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/ServiceCollectionExtensions.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/ServiceCollectionExtensions.cs new file mode 100644 index 000000000..eae0fee63 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/ServiceCollectionExtensions.cs @@ -0,0 +1,108 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller; + +public static class ServiceCollectionExtensions +{ + public static IServiceCollection AddCaller(this IServiceCollection services) + => services.AddCaller(AppDomain.CurrentDomain.GetAssemblies()); + + public static IServiceCollection AddCaller(this IServiceCollection services, params Assembly[] assemblies) + => services.AddCaller(options => options.Assemblies = assemblies); + + private static IServiceCollection AddCaller(this IServiceCollection services, + ServiceLifetime lifetime = ServiceLifetime.Scoped, + params Assembly[] assemblies) + => services.AddCaller(options => + { + options.Assemblies = assemblies; + options.CallerLifetime = lifetime; + }); + + public static IServiceCollection AddCaller(this IServiceCollection services, Action options) + { + CallerOptions callerOption = new CallerOptions(services); + options.Invoke(callerOption); + + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddScoped(serviceProvider => serviceProvider.GetRequiredService().CreateClient()); + + services.TryAddSingleton(); + services.AddAutomaticCaller(callerOption); + TryOrUpdateCallerOptions(services, callerOption); + return services; + } + + private static void AddAutomaticCaller(this IServiceCollection services, CallerOptions callerOptions) + { + var callerTypes = callerOptions.Assemblies.SelectMany(x => x.GetTypes()) + .Where(type => typeof(CallerBase).IsAssignableFrom(type) && !type.IsAbstract).ToList(); + + callerTypes = callerTypes.Except(services.Select(d => d.ServiceType)).ToList(); + + if (callerTypes.Count == 0) + return; + + callerTypes.Arrangement().ForEach(type => + { + ServiceDescriptor serviceDescriptor = new ServiceDescriptor(type, serviceProvider => + { + var constructorInfo = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) + .MaxBy(constructor => constructor.GetParameters().Length)!; + List parameters = new(); + foreach (var parameter in constructorInfo.GetParameters()) + { + parameters.Add(serviceProvider.GetRequiredService(parameter.ParameterType)); + } + var callerBase = (constructorInfo.Invoke(parameters.ToArray()) as CallerBase)!; + callerBase.SetCallerOptions(callerOptions, type.FullName ?? type.Name); + return callerBase; + }, callerOptions.CallerLifetime); + services.TryAdd(serviceDescriptor); + }); + + var serviceProvider = services.BuildServiceProvider(); + callerTypes.ForEach(type => + { + var callerBase = (CallerBase)serviceProvider.GetRequiredService(type); + callerBase.UseCallerExtension(); + }); + } + + private static IServiceCollection TryOrUpdateCallerOptions(this IServiceCollection services, CallerOptions options) + { + services.Configure(callerOptions => + { + options.Callers.ForEach(caller => + { + if (callerOptions.Callers.Any(relation => relation.Name == caller.Name)) + throw new ArgumentException($"The caller name already exists, please change the name, the repeat name is [{caller.Name}]"); + + if (callerOptions.Callers.Any(relation => relation.IsDefault && caller.IsDefault)) + { + string errorCallerNames = string.Join("、", callerOptions.Callers + .Where(relation => relation.IsDefault) + .Select(relation => relation.Name) + .Concat(options.Callers.Where(relation => relation.IsDefault).Select(relation => relation.Name)) + .Distinct()); + throw new ArgumentException( + $"There can only be at most one default Caller Provider, and now the following Caller Providers are found to be default: {errorCallerNames}"); + } + + callerOptions.Callers.Add(caller); + }); + + if (callerOptions.JsonSerializerOptions == null && options.JsonSerializerOptions != null) + callerOptions.JsonSerializerOptions = options.JsonSerializerOptions; + + if (callerOptions.RequestIdKey != null && options.RequestIdKey != null) + callerOptions.RequestIdKey = options.RequestIdKey; + }); + + return services; + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/_Imports.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/_Imports.cs new file mode 100644 index 000000000..e936bf497 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/_Imports.cs @@ -0,0 +1,20 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +global using Masa.BuildingBlocks.Service.Caller; +global using Masa.BuildingBlocks.Service.Caller.Options; +global using Masa.Contrib.Service.Caller.Internal; +global using Masa.Contrib.Service.Caller.Internal.Options; +global using Masa.Utils.Exceptions; +global using Microsoft.AspNetCore.Http; +global using Microsoft.Extensions.DependencyInjection; +global using Microsoft.Extensions.DependencyInjection.Extensions; +global using Microsoft.Extensions.Logging; +global using Microsoft.Extensions.Options; +global using System.Collections.Concurrent; +global using System.Net; +global using System.Net.Http.Json; +global using System.Reflection; +global using System.Runtime.ExceptionServices; +global using System.Text.Json; +global using System.Text.Json.Serialization; diff --git a/test/Masa.Contrib.Configuration.Tests/Masa.Contrib.Configuration.Tests.csproj b/test/Masa.Contrib.Configuration.Tests/Masa.Contrib.Configuration.Tests.csproj index 5d9744d65..c7631538c 100644 --- a/test/Masa.Contrib.Configuration.Tests/Masa.Contrib.Configuration.Tests.csproj +++ b/test/Masa.Contrib.Configuration.Tests/Masa.Contrib.Configuration.Tests.csproj @@ -35,9 +35,6 @@ Always - - Always - Always @@ -45,10 +42,6 @@ Always - - - Always - diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/AutomaticCallerTest.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/AutomaticCallerTest.cs new file mode 100644 index 000000000..621ac7bfd --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/AutomaticCallerTest.cs @@ -0,0 +1,47 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.AutomaticCaller.Tests; + +[TestClass] +public class AutomaticCallerTest +{ + private WebApplicationBuilder _builder = default!; + + [TestInitialize] + public void EdgeDriverInitialize() + { + _builder = WebApplication.CreateBuilder(); + } + + [TestMethod] + public async Task TestGetAsync() + { + _builder.Services.AddCaller(); + _ = _builder.Build(); + var serviceProvider = _builder.Services.BuildServiceProvider(); + var githubCaller = serviceProvider.GetRequiredService(); + Assert.IsTrue(await githubCaller.GetAsync()); + } + + [TestMethod] + public void TestDaprCallerReturnCallerProviderIsNotNull() + { + _builder.Services.AddCaller(); + _ = _builder.Build(); + var serviceProvider = _builder.Services.BuildServiceProvider(); + var caller = serviceProvider.GetRequiredService(); + Assert.IsTrue(caller.CallerProviderIsNotNull()); + } + + [TestMethod] + public void TestCustomDaprBaseReturnAppIdIsEqualUserService() + { + _builder.Services.AddCaller(); + _ = _builder.Build(); + var serviceProvider = _builder.Services.BuildServiceProvider(); + var roleCaller = serviceProvider.GetRequiredService(); + var userCaller = serviceProvider.GetRequiredService(); + Assert.IsTrue(roleCaller.GetAppId() == "User-Service" && userCaller.GetAppId() == "User-Service"); + } +} diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/CallerTest.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/CallerTest.cs new file mode 100644 index 000000000..e38262ea1 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/CallerTest.cs @@ -0,0 +1,217 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +using Masa.BuildingBlocks.Service.Caller.Options; +using Microsoft.Extensions.Options; + +namespace Masa.Contrib.Service.Caller.AutomaticCaller.Tests; + +[TestClass] +public class CallerTest +{ + [TestMethod] + public void TestCallerProviderServiceLifetime() + { + IServiceCollection services = new ServiceCollection(); + services.AddCaller(opt => + { + opt.UseHttpClient(clientBuilder => + { + clientBuilder.Name = "http"; + clientBuilder.IsDefault = true; + clientBuilder.BaseAddress = "https://github.com/masastack/MASA.Contrib"; + }); + }); + var serviceProvider = services.BuildServiceProvider(); + var callerProvider1 = serviceProvider.GetRequiredService(); + var callerProvider2 = serviceProvider.GetRequiredService(); + Assert.IsTrue(callerProvider1 == callerProvider2); + } + + [TestMethod] + public void TestCaller() + { + IServiceCollection services = new ServiceCollection(); + services.AddCaller(opt => + { + opt.UseHttpClient(clientBuilder => + { + clientBuilder.Name = "http"; + clientBuilder.IsDefault = true; + clientBuilder.BaseAddress = "https://github.com/masastack/MASA.Contrib"; + }); + opt.UseDapr(clientBuilder => + { + clientBuilder.Name = "dapr"; + clientBuilder.IsDefault = false; + }); + }); + var serviceProvider = services.BuildServiceProvider(); + var callerProvider = serviceProvider.GetRequiredService(); + Assert.IsNotNull(callerProvider); + + var caller = serviceProvider.GetRequiredService().CreateClient(); + var daprCaller = serviceProvider.GetRequiredService().CreateClient("dapr"); + var httpCaller = serviceProvider.GetRequiredService().CreateClient("http"); + + Assert.IsTrue(caller.GetType().FullName != daprCaller.GetType().FullName); + Assert.IsTrue(caller.GetType().FullName == httpCaller.GetType().FullName); + } + + [TestMethod] + public void TestMultiDefaultCaller() + { + IServiceCollection services = new ServiceCollection(); + + services.AddCaller(opt => + { + opt.UseHttpClient(builder => + { + builder.Name = "github"; + builder.BaseAddress = "https://github.com/masastack"; + builder.IsDefault = true; + }); + opt.UseHttpClient(builder => + { + builder.Name = "gitee"; + builder.BaseAddress = "https://gitee.com/masastack"; + builder.IsDefault = true; + }); + }); + var serviceProvider = services.BuildServiceProvider(); + Assert.ThrowsException(() => + { + var optionsFactory = serviceProvider.GetRequiredService>(); + optionsFactory.Create(Options.DefaultName); + }); + } + + [TestMethod] + public void TestMultiDefaultCaller2() + { + IServiceCollection services = new ServiceCollection(); + services.AddCaller(opt => + { + opt.UseHttpClient(builder => + { + builder.Name = "gitee"; + builder.BaseAddress = "https://gitee.com/masastack"; + builder.IsDefault = true; + }); + }); + services.AddCaller(opt => + { + opt.UseHttpClient(builder => + { + builder.Name = "github"; + builder.BaseAddress = "https://github.com/masastack"; + builder.IsDefault = true; + }); + }); + var serviceProvider = services.BuildServiceProvider(); + Assert.ThrowsException(() => + { + var optionsFactory = serviceProvider.GetRequiredService>(); + optionsFactory.Create(Options.DefaultName); + }); + } + + [TestMethod] + public void TestRepeatCallerName() + { + IServiceCollection services = new ServiceCollection(); + Assert.ThrowsException(() => + { + services.AddCaller(opt => + { + opt.UseHttpClient(builder => + { + builder.Name = "github"; + builder.BaseAddress = "https://github.com/masastack"; + builder.IsDefault = true; + }); + opt.UseHttpClient(builder => + { + builder.Name = "github"; + builder.BaseAddress = "https://github.com/masastack"; + builder.IsDefault = true; + }); + }); + }); + } + + [TestMethod] + public void TestRepeatCallerName2() + { + IServiceCollection services = new ServiceCollection(); + services.AddCaller(opt => + { + opt.UseHttpClient(builder => + { + builder.Name = "github"; + builder.BaseAddress = "https://github.com/masastack"; + builder.IsDefault = true; + }); + }); + + services.AddCaller(opt => + { + opt.UseHttpClient(builder => + { + builder.Name = "github"; + builder.BaseAddress = "https://github.com/masastack"; + builder.IsDefault = true; + }); + }); + var serviceProvider = services.BuildServiceProvider(); + Assert.ThrowsException(() => + { + var optionsFactory = serviceProvider.GetRequiredService>(); + optionsFactory.Create(Options.DefaultName); + }); + } + + [TestMethod] + public void TestRepeatCallerName3() + { + IServiceCollection services = new ServiceCollection(); + Assert.ThrowsException(() => + { + services.AddCaller(opt => + { + opt.UseHttpClient(builder => + { + builder.Name = typeof(GithubCaller).FullName!; + builder.BaseAddress = "https://github.com/masastack"; + builder.IsDefault = true; + }); + }); + }); + } + + [TestMethod] + public void TestAddMultiCaller() + { + IServiceCollection services = new ServiceCollection(); + services.AddCaller(opt => + { + opt.UseHttpClient(builder => + { + builder.Name = "masastack"; + builder.BaseAddress = "https://github.com/masastack"; + builder.IsDefault = true; + }); + }); + services.AddCaller(opt => + { + opt.UseHttpClient(builder => + { + builder.Name = "masastack2"; + builder.BaseAddress = "https://github.com/masastack"; + }); + }); + var serviceProvider = services.BuildServiceProvider(); + Assert.IsNotNull(serviceProvider.GetRequiredService().CreateClient("masastack")); + Assert.IsNotNull(serviceProvider.GetRequiredService().CreateClient("masastack2")); + } +} diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/DaprCaller.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/DaprCaller.cs new file mode 100644 index 000000000..a3662f200 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/DaprCaller.cs @@ -0,0 +1,16 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.AutomaticCaller.Tests.Callers; + +public class DaprCaller : DaprCallerBase +{ + public DaprCaller(IServiceProvider serviceProvider) : base(serviceProvider) + { + AppId = "DaprCaller"; + } + + protected override string AppId { get; set; } + + public bool CallerProviderIsNotNull() => CallerProvider != null; +} diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/GithubCaller.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/GithubCaller.cs new file mode 100644 index 000000000..d10a461a5 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/GithubCaller.cs @@ -0,0 +1,20 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.AutomaticCaller.Tests.Callers; + +public class GithubCaller : HttpClientCallerBase +{ + public GithubCaller(IServiceProvider serviceProvider) : base(serviceProvider) + { + BaseAddress = "https://github.com/masastack"; + } + + protected override string BaseAddress { get; set; } + + public async Task GetAsync() + { + var res = await CallerProvider.GetAsync(""); + return res.IsSuccessStatusCode && res.StatusCode == HttpStatusCode.OK; + } +} diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/RoleCaller.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/RoleCaller.cs new file mode 100644 index 000000000..be679e60c --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/RoleCaller.cs @@ -0,0 +1,11 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.AutomaticCaller.Tests.Callers; + +public class RoleCaller: UserDaprCallerBase +{ + public RoleCaller(IServiceProvider serviceProvider) : base(serviceProvider) + { + } +} diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/UserCaller.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/UserCaller.cs new file mode 100644 index 000000000..6bfbbd7ae --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/UserCaller.cs @@ -0,0 +1,11 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.AutomaticCaller.Tests.Callers; + +public class UserCaller : UserDaprCallerBase +{ + public UserCaller(IServiceProvider serviceProvider) : base(serviceProvider) + { + } +} diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/UserDaprCallerBase.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/UserDaprCallerBase.cs new file mode 100644 index 000000000..de2b5eb55 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/UserDaprCallerBase.cs @@ -0,0 +1,29 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.AutomaticCaller.Tests.Callers; + +public abstract class UserDaprCallerBase : DaprCallerBase +{ + protected override string AppId { get; set; } = "User-Service"; + + protected UserDaprCallerBase(IServiceProvider serviceProvider) : base(serviceProvider) + { + } + + public string GetAppId() => AppId; + + protected override DefaultDaprClientBuilder UseDapr() + { + return base.UseDapr().AddHttpRequestMessage(); + } +} + +public class DefaultDaprRequestMessage : IDaprRequestMessage +{ + public Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage) + { + requestMessage.Headers.Add("test", "test"); + return Task.FromResult(requestMessage); + } +} diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Masa.Contrib.Service.Caller.AutomaticCaller.Tests.csproj b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Masa.Contrib.Service.Caller.AutomaticCaller.Tests.csproj new file mode 100644 index 000000000..6c4f3a01d --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Masa.Contrib.Service.Caller.AutomaticCaller.Tests.csproj @@ -0,0 +1,28 @@ + + + + net6.0 + enable + enable + false + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/_Imports.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/_Imports.cs new file mode 100644 index 000000000..bb4252613 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/_Imports.cs @@ -0,0 +1,11 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +global using Masa.BuildingBlocks.Service.Caller; +global using Masa.Contrib.Service.Caller.AutomaticCaller.Tests.Callers; +global using Masa.Contrib.Service.Caller.DaprClient; +global using Masa.Contrib.Service.Caller.HttpClient; +global using Microsoft.AspNetCore.Builder; +global using Microsoft.Extensions.DependencyInjection; +global using Microsoft.VisualStudio.TestTools.UnitTesting; +global using System.Net; diff --git a/test/Masa.Contrib.Service.Caller.Tests/CallerTest.cs b/test/Masa.Contrib.Service.Caller.Tests/CallerTest.cs new file mode 100644 index 000000000..657779c11 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/CallerTest.cs @@ -0,0 +1,138 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Tests; + +[TestClass] +public class CallerTest +{ + private WebApplicationBuilder _builder = default!; + + [TestInitialize] + public void EdgeDriverInitialize() + { + _builder = WebApplication.CreateBuilder(); + } + + [TestMethod] + public async Task TestGetAsync() + { + _builder.Services.AddCaller(callerOptions => + { + callerOptions.UseHttpClient(httpClientBuilder => + { + httpClientBuilder.Configure = builder => builder.Timeout = TimeSpan.FromSeconds(3); + httpClientBuilder.BaseAddress = "https://github.com/masastack"; + }); + }); + _ = _builder.Build(); + var serviceProvider = _builder.Services.BuildServiceProvider(); + var githubCaller = serviceProvider.GetRequiredService(); + Assert.IsTrue(await GetAsync(githubCaller)); + } + + private async Task GetAsync(ICallerProvider callerProvider) + { + var res = await callerProvider.GetAsync(""); + return res.IsSuccessStatusCode && res.StatusCode == HttpStatusCode.OK; + } + + [TestMethod] + public void TestConvertToDictionaryByDynamic() + { + var provider = new DefaultTypeConvertProvider(); + var dictionary = new Dictionary + { + { "account", "jim" }, + { "age", "18" } + }; + var request = new + { + account = "jim", + age = 18 + }; + var result = provider.ConvertToDictionary(request); + Assert.IsTrue(System.Text.Json.JsonSerializer.Serialize(result) == System.Text.Json.JsonSerializer.Serialize(dictionary)); + } + + [TestMethod] + public void TestConvertToDictionaryByObject() + { + var provider = new DefaultTypeConvertProvider(); + var query = new UserListQuery("Jim"); + var dictionary = new Dictionary + { + { "name", query.Name } + }; + var result = provider.ConvertToDictionary(query); + Assert.IsTrue(System.Text.Json.JsonSerializer.Serialize(result) == System.Text.Json.JsonSerializer.Serialize(dictionary)); + } + + [TestMethod] + public void TestConvertToDictionaryByObject2() + { + var provider = new DefaultTypeConvertProvider(); + var query = new UserDetailQuery("Jim", "Music", "Game"); + var result = provider.ConvertToDictionary(query); + Assert.IsTrue(result.Count == 2); + Assert.IsTrue(result["name"] == query.Name); + Assert.IsTrue(result["Tags"] == System.Text.Json.JsonSerializer.Serialize(new List() + { + "Music", + "Game" + })); + } + + [TestMethod] + public void TestConvertToDictionaryByObject3() + { + var provider = new DefaultTypeConvertProvider(); + + List tags = null!; + var query = new UserDetailQuery("Jim", tags); + var result = provider.ConvertToDictionary(query); + + Assert.IsTrue(result.Count == 1); + Assert.IsTrue(result["name"] == query.Name); + } + + [TestMethod] + public void TestConvertToDictionaryByObject4() + { + var provider = new DefaultTypeConvertProvider(); + var query = new UserDetailQuery(null!, "Music", "Game"); + var result = provider.ConvertToDictionary(query); + Assert.IsTrue(result.Count == 1); + Assert.IsTrue(result["Tags"] == System.Text.Json.JsonSerializer.Serialize(new List() + { + "Music", + "Game" + })); + } + + [TestMethod] + public void TestConvertToDictionaryByObject5() + { + var provider = new DefaultTypeConvertProvider(); + var dic = new Dictionary() + { + { "Account", "Jim" } + }; + var result = provider.ConvertToDictionary(dic); + Assert.IsTrue(result.Count == 1); + Assert.IsTrue(result["Account"] == "Jim"); + } + + [TestMethod] + public void TestConvertToDictionaryByObject6() + { + var provider = new DefaultTypeConvertProvider(); + var dic = new List>() + { + new("Account", "Jim") + }; + var result = provider.ConvertToDictionary(dic); + Assert.IsTrue(result.Count == 1); + Assert.IsTrue(result["Account"] == "Jim"); + } +} diff --git a/test/Masa.Contrib.Service.Caller.Tests/CustomHttpClientCallerProvider.cs b/test/Masa.Contrib.Service.Caller.Tests/CustomHttpClientCallerProvider.cs new file mode 100644 index 000000000..a1273f851 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/CustomHttpClientCallerProvider.cs @@ -0,0 +1,14 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Tests; + +public class CustomHttpClientCallerProvider : HttpClientCallerProvider +{ + public CustomHttpClientCallerProvider(IServiceProvider serviceProvider, string name, string baseApi) + : base(serviceProvider, name, baseApi) + { + } + + public string GetResult(string? methodName) => base.GetRequestUri(methodName); +} diff --git a/test/Masa.Contrib.Service.Caller.Tests/DefaultXmlResponseMessage.cs b/test/Masa.Contrib.Service.Caller.Tests/DefaultXmlResponseMessage.cs new file mode 100644 index 000000000..50876a30a --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/DefaultXmlResponseMessage.cs @@ -0,0 +1,91 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Tests; + +public class DefaultXmlResponseMessage : IResponseMessage +{ + private readonly ILogger? _logger; + + public DefaultXmlResponseMessage(ILogger? logger = null) + { + _logger = logger; + } + + public async Task ProcessResponseAsync(HttpResponseMessage response, + CancellationToken cancellationToken = default) + { + if (response.IsSuccessStatusCode) + { + switch (response.StatusCode) + { + case HttpStatusCode.Accepted: + case HttpStatusCode.NoContent: + return default; + case (HttpStatusCode)MasaHttpStatusCode.UserFriendlyException: + throw new UserFriendlyException(await response.Content.ReadAsStringAsync(cancellationToken)); + default: + if (typeof(TResponse) == typeof(Guid) || typeof(TResponse) == typeof(Guid?)) + { + var content = await response.Content.ReadAsStringAsync(cancellationToken); + if (string.IsNullOrEmpty(content)) + return (TResponse)(object?)null!; + + return (TResponse?)(object)Guid.Parse(content.Replace("\"", "")); + } + if (typeof(TResponse) == typeof(DateTime) || typeof(TResponse) == typeof(DateTime?)) + { + var content = await response.Content.ReadAsStringAsync(cancellationToken); + if (string.IsNullOrEmpty(content)) + return (TResponse)(object?)null!; + + return (TResponse?)(object)DateTime.Parse(content.Replace("\"", "")); + } + if (typeof(TResponse).GetInterfaces().Any(type => type == typeof(IConvertible))) + { + var content = await response.Content.ReadAsStringAsync(cancellationToken); + return (TResponse)Convert.ChangeType(content, typeof(TResponse)); + } + try + { + var res = await response.Content.ReadAsStringAsync(cancellationToken); + return XmlUtils.Deserialize(res) ?? + throw new ArgumentException("The response cannot be empty or there is an error in deserialization"); + } + catch (Exception exception) + { + _logger?.LogWarning(exception, exception.Message); + ExceptionDispatchInfo.Capture(exception).Throw(); + return default; //This will never be executed, the previous line has already thrown an exception + } + } + } + + await ProcessResponseExceptionAsync(response, cancellationToken); + return default; //never executed + } + + public async Task ProcessResponseAsync(HttpResponseMessage response, CancellationToken cancellationToken = default) + { + if (response.IsSuccessStatusCode) + { + switch (response.StatusCode) + { + case (HttpStatusCode)MasaHttpStatusCode.UserFriendlyException: + throw new UserFriendlyException(await response.Content.ReadAsStringAsync(cancellationToken)); + default: + return; + } + } + + await ProcessResponseExceptionAsync(response, cancellationToken); + } + + public async Task ProcessResponseExceptionAsync(HttpResponseMessage response, CancellationToken cancellationToken = default) + { + if (response.Content.Headers.ContentLength is > 0) + throw new Exception(await response.Content.ReadAsStringAsync(cancellationToken)); + + throw new MasaException($"ReasonPhrase: {response.ReasonPhrase ?? string.Empty}, StatusCode: {response.StatusCode}"); + } +} diff --git a/test/Masa.Contrib.Service.Caller.Tests/HttpClientCallerTest.cs b/test/Masa.Contrib.Service.Caller.Tests/HttpClientCallerTest.cs new file mode 100644 index 000000000..433247909 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/HttpClientCallerTest.cs @@ -0,0 +1,128 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Tests; + +[TestClass] +public class HttpClientCallerTest +{ + [DataTestMethod] + [DataRow("https://github.com/", "/check/healthy", "https://github.com/check/healthy")] + [DataRow("https://github.com", "/check/healthy", "https://github.com/check/healthy")] + [DataRow("https://github.com", "check/healthy", "https://github.com/check/healthy")] + [DataRow("https://github.com/check", "healthy", "https://github.com/check/healthy")] + [DataRow("https://github.com/check/", "healthy", "https://github.com/check/healthy")] + [DataRow("https://github.com/check/", "/healthy", "https://github.com/check/healthy")] + [DataRow("https://github.com/check/", "/healthy?date=1650465417", "https://github.com/check/healthy?date=1650465417")] + [DataRow("https://github.com/check/", "healthy?date=1650465417", "https://github.com/check/healthy?date=1650465417")] + [DataRow("https://github.com/check", "healthy?date=1650465417", "https://github.com/check/healthy?date=1650465417")] + [DataRow("https://github.com", "https://github.com/check/healthy?date=1650465417", "https://github.com/check/healthy?date=1650465417")] + [DataRow("https://github.com", "", "")] + [DataRow("http://github.com", "", "")] + [DataRow("/v1/check", "healthy", "/v1/check/healthy")] + [DataRow("/v1/check/", "healthy", "/v1/check/healthy")] + [DataRow("/v1/check/", "/healthy", "/v1/check/healthy")] + [DataRow("/v1/check/", "/healthy", "/v1/check/healthy")] + [DataRow("/v1/check/", "https://github.com/check/healthy?date=1650465417", "https://github.com/check/healthy?date=1650465417")] + [DataRow("", "healthy", "healthy")] + [DataRow("", "/healthy?id=1", "/healthy?id=1")] + public void TestGetRequestUri(string prefix, string methods, string result) + { + var services = new ServiceCollection(); + services.AddCaller(opt => opt.UseHttpClient()); + var serviceProvider = services.BuildServiceProvider(); + var provider = new CustomHttpClientCallerProvider(serviceProvider, string.Empty, prefix); + Assert.IsTrue(provider.GetResult(methods) == result); + } + + [TestMethod] + public async Task TestRequestDataIsXmlAsync() + { + var services = new ServiceCollection(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + Mock httpClientFactory = new(); + var handlerMock = new Mock(); + var magicHttpClient = new System.Net.Http.HttpClient(handlerMock.Object) + { + BaseAddress = new Uri("http://localhost:5000") + }; + var response = new BaseResponse("success"); + handlerMock + .Protected() + .Setup>( + "SendAsync", + ItExpr.IsAny(), + ItExpr.IsAny() + ) + .ReturnsAsync(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(XmlUtils.Serializer(response)) + }) + .Verifiable(); + + httpClientFactory.Setup(factory => factory.CreateClient(It.IsAny())).Returns(magicHttpClient); + services.AddSingleton(httpClientFactory.Object); + var serviceProvider = services.BuildServiceProvider(); + string name = ""; + string prefix = ""; + var httpClientCallerProvider = new HttpClientCallerProvider(serviceProvider, name, prefix); + + var res = await httpClientCallerProvider.PostAsync("Hello", new RegisterUser("Jim", "123456")); + Assert.IsNotNull(res); + Assert.IsTrue(res.Code == response.Code); + } + + [TestMethod] + public async Task TestRequestMessageReturnOnceAsync() + { + var services = new ServiceCollection(); + RegisterUser registerUser = new RegisterUser("Jim", "123456"); + + services.AddSingleton(); + Mock requestMessage = new(); + requestMessage.Setup(req => req.ProcessHttpRequestMessageAsync(It.IsAny())) + .ReturnsAsync(new HttpRequestMessage(HttpMethod.Post, "Hello")).Verifiable(); + requestMessage.Setup(req => req.ProcessHttpRequestMessageAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(new HttpRequestMessage(HttpMethod.Post, "Hello") + { + Content = JsonContent.Create(registerUser) + }).Verifiable(); + services.AddSingleton(_ => requestMessage.Object); + services.AddSingleton(); + Mock httpClientFactory = new(); + var handlerMock = new Mock(); + var magicHttpClient = new System.Net.Http.HttpClient(handlerMock.Object) + { + BaseAddress = new Uri("http://localhost:5000") + }; + var response = new BaseResponse("success"); + handlerMock + .Protected() + .Setup>( + "SendAsync", + ItExpr.IsAny(), + ItExpr.IsAny() + ) + .ReturnsAsync(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(XmlUtils.Serializer(response)) + }) + .Verifiable(); + + httpClientFactory.Setup(factory => factory.CreateClient(It.IsAny())).Returns(magicHttpClient); + services.AddSingleton(httpClientFactory.Object); + var serviceProvider = services.BuildServiceProvider(); + string name = ""; + string prefix = ""; + var httpClientCallerProvider = new HttpClientCallerProvider(serviceProvider, name, prefix); + + var res = await httpClientCallerProvider.PostAsync("Hello", registerUser); + Assert.IsNotNull(res); + Assert.IsTrue(res.Code == response.Code); + requestMessage.Verify(r => r.ProcessHttpRequestMessageAsync(It.IsAny(), It.IsAny()), Times.Once); + } +} diff --git a/test/Masa.Contrib.Service.Caller.Tests/Masa.Contrib.Service.Caller.Tests.csproj b/test/Masa.Contrib.Service.Caller.Tests/Masa.Contrib.Service.Caller.Tests.csproj new file mode 100644 index 000000000..6286e0fc0 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/Masa.Contrib.Service.Caller.Tests.csproj @@ -0,0 +1,24 @@ + + + + net6.0 + enable + enable + false + + + + + + + + + + + + + + + + + diff --git a/test/Masa.Contrib.Service.Caller.Tests/Queries/UserDetailQuery.cs b/test/Masa.Contrib.Service.Caller.Tests/Queries/UserDetailQuery.cs new file mode 100644 index 000000000..e4bf3d726 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/Queries/UserDetailQuery.cs @@ -0,0 +1,34 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Tests.Queries; + +public class UserDetailQuery +{ + public Guid? Id { get; set; } + + [JsonPropertyName("name")] + public string? Name { get; set; } + + [JsonIgnore] + public int Age { get; set; } + + public DateTime? DelTime { get; set; } + + public List? Tags { get; set; } + + public UserDetailQuery() + { + this.Id = Guid.NewGuid(); + } + + public UserDetailQuery(string name, params string[] tags) : this(name, tags.ToList()) + { + } + + public UserDetailQuery(string name, List tags) + { + Name = name; + Tags = tags; + } +} diff --git a/test/Masa.Contrib.Service.Caller.Tests/Queries/UserListQuery.cs b/test/Masa.Contrib.Service.Caller.Tests/Queries/UserListQuery.cs new file mode 100644 index 000000000..1d10b319d --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/Queries/UserListQuery.cs @@ -0,0 +1,18 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Tests.Queries; + +public class UserListQuery +{ + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonIgnore] + public int Age { get; set; } + + public UserListQuery(string name) + { + Name = name; + } +} diff --git a/test/Masa.Contrib.Service.Caller.Tests/Requesties/RegisterUser.cs b/test/Masa.Contrib.Service.Caller.Tests/Requesties/RegisterUser.cs new file mode 100644 index 000000000..c2797a77d --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/Requesties/RegisterUser.cs @@ -0,0 +1,22 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Tests.Requesties; + +[XmlRoot] +public class RegisterUser +{ + [XmlElement] + public string Account { get; set; } = default!; + + [XmlElement] + public string Password { get; set; } = default!; + + public RegisterUser() { } + + public RegisterUser(string account, string password) : this() + { + Account = account; + Password = password; + } +} diff --git a/test/Masa.Contrib.Service.Caller.Tests/Response/BaseResponse.cs b/test/Masa.Contrib.Service.Caller.Tests/Response/BaseResponse.cs new file mode 100644 index 000000000..9b51b19b2 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/Response/BaseResponse.cs @@ -0,0 +1,16 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Tests.Response; + +[Serializable] +[XmlRoot] +public class BaseResponse +{ + [XmlElement] + public string Code { get; set; } = default!; + + public BaseResponse() { } + + public BaseResponse(string code) { Code = code; } +} diff --git a/test/Masa.Contrib.Service.Caller.Tests/TypeConvertTest.cs b/test/Masa.Contrib.Service.Caller.Tests/TypeConvertTest.cs new file mode 100644 index 000000000..3b06891f3 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/TypeConvertTest.cs @@ -0,0 +1,30 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Tests; + +[TestClass] +public class TypeConvertTest +{ + [TestMethod] + public void TestConvertToKeyValuePairs() + { + var defaultTypeConvertProvider = new DefaultTypeConvertProvider(); + var result = defaultTypeConvertProvider.ConvertToKeyValuePairs(new + { + id = 1, + name = "masa" + }).ToList(); + Assert.AreEqual(2, result.Count()); + Assert.IsTrue(result.Any(x => x.Key == "id" && x.Value == "1")); + Assert.IsTrue(result.Any(x => x.Key == "name" && x.Value == "masa")); + + result = defaultTypeConvertProvider.ConvertToKeyValuePairs(new + { + id = 2, + text = "masa" + }).ToList(); + Assert.IsTrue(result.Any(x => x.Key == "id" && x.Value == "2")); + Assert.IsTrue(result.Any(x => x.Key == "text" && x.Value == "masa")); + } +} diff --git a/test/Masa.Contrib.Service.Caller.Tests/Utils/XmlUtils.cs b/test/Masa.Contrib.Service.Caller.Tests/Utils/XmlUtils.cs new file mode 100644 index 000000000..86bbfbdb3 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/Utils/XmlUtils.cs @@ -0,0 +1,23 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Tests.Utils; + +public class XmlUtils +{ + public static string Serializer(object data) + { + MemoryStream ms = new MemoryStream(); + StreamWriter sw = new StreamWriter(ms, Encoding.UTF8); + XmlSerializer xz = new XmlSerializer(data.GetType()); + xz.Serialize(sw, data); + return Encoding.UTF8.GetString(ms.ToArray()); + } + + public static T Deserialize(string xml) + { + XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); + using MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml.ToCharArray())); + return (T)xmlSerializer.Deserialize(stream)!; + } +} diff --git a/test/Masa.Contrib.Service.Caller.Tests/XmlRequestMessage.cs b/test/Masa.Contrib.Service.Caller.Tests/XmlRequestMessage.cs new file mode 100644 index 000000000..dbdfb93b9 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/XmlRequestMessage.cs @@ -0,0 +1,17 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Tests; + +public class XmlRequestMessage : IRequestMessage +{ + public Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage) + => Task.FromResult(requestMessage); + + public Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage, TRequest data) + { + var xmlContent = XmlUtils.Serializer(data!); + requestMessage.Content = new StringContent(xmlContent); + return Task.FromResult(requestMessage); + } +} diff --git a/test/Masa.Contrib.Service.Caller.Tests/_Imports.cs b/test/Masa.Contrib.Service.Caller.Tests/_Imports.cs new file mode 100644 index 000000000..7a92e736e --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.Tests/_Imports.cs @@ -0,0 +1,22 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +global using Masa.BuildingBlocks.Service.Caller; +global using Masa.Contrib.Service.Caller.HttpClient; +global using Masa.Contrib.Service.Caller.Tests.Queries; +global using Masa.Contrib.Service.Caller.Tests.Requesties; +global using Masa.Contrib.Service.Caller.Tests.Response; +global using Masa.Contrib.Service.Caller.Tests.Utils; +global using Masa.Utils.Exceptions; +global using Microsoft.AspNetCore.Builder; +global using Microsoft.Extensions.DependencyInjection; +global using Microsoft.Extensions.Logging; +global using Microsoft.VisualStudio.TestTools.UnitTesting; +global using Moq; +global using Moq.Protected; +global using System.Net; +global using System.Net.Http.Json; +global using System.Runtime.ExceptionServices; +global using System.Text; +global using System.Text.Json.Serialization; +global using System.Xml.Serialization; From 7418875960dbb6acacbc5c8e44853aac13af3801 Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Tue, 26 Jul 2022 11:39:20 +0800 Subject: [PATCH 02/13] fix(Configuration.Dcc): Fix ConfigurationManager to get inappropriate CallerProvider --- Masa.Contrib.sln | 2 +- .../Internal/DccFactory.cs | 4 ++-- ...trib.Configuration.ConfigurationApi.Dcc.csproj | 3 ++- .../MasaConfigurationExtensions.cs | 15 +++++++++------ .../_Imports.cs | 7 ++++--- .../DccManageTest.cs | 2 ++ .../DccTest.cs | 13 +++++++++++-- .../_Imports.cs | 6 +++--- 8 files changed, 34 insertions(+), 18 deletions(-) diff --git a/Masa.Contrib.sln b/Masa.Contrib.sln index 71f31e753..b040bb3fe 100644 --- a/Masa.Contrib.sln +++ b/Masa.Contrib.sln @@ -1557,7 +1557,6 @@ Global {AA7876FF-3EF9-40EC-B5FF-66AB748DB93E} = {5F25960E-646D-4EA6-A648-3CAD284B6E38} {DB2B4DA3-EEF2-49AA-93A4-B00C25210A68} = {38E6C400-90C0-493E-9266-C1602E229F1B} {23582B50-BAEA-4A2D-82A4-345A3C30124E} = {59DA3D5F-9E39-4173-8C31-126967CC189F} - {1371F22B-FDD7-43B0-8E7D-E68DA31F07F3} = {38E6C400-90C0-493E-9266-C1602E229F1B} {FF3FD53D-D23E-48AC-98B6-3B028B4DE8AF} = {0D34A7F0-DC77-4789-A136-93089CBD15C3} {83FA668F-C838-4883-996D-AF2ECF00FDF8} = {5DFAF4A2-ECB5-46E4-904D-1EA5F48B2D48} {789ABED5-7C94-4F6F-ADCA-E97F3DFC9479} = {38E6C400-90C0-493E-9266-C1602E229F1B} @@ -1589,6 +1588,7 @@ Global {A5C1EF6B-A3B5-4D0C-8373-F854EE7EF4AD} = {4AA6B450-D4AA-4474-9ECF-52A44935D8D9} {D855894E-4C72-41DC-8F84-EF66CDE37453} = {4AA6B450-D4AA-4474-9ECF-52A44935D8D9} {1EE45374-EF8E-4E9D-A74F-51C14DA58ED8} = {4AA6B450-D4AA-4474-9ECF-52A44935D8D9} + {1371F22B-FDD7-43B0-8E7D-E68DA31F07F3} = {9EEE31DA-3165-4CB3-AAE9-27CC3A4DE669} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {40383055-CC50-4600-AD9A-53C14F620D03} diff --git a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Internal/DccFactory.cs b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Internal/DccFactory.cs index 916ef1140..ee87fa6b0 100644 --- a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Internal/DccFactory.cs +++ b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Internal/DccFactory.cs @@ -16,8 +16,8 @@ public static IConfigurationApiClient CreateClient( } public static IConfigurationApiManage CreateManage( - ICallerFactory callerFactory, + ICallerProvider callerProvider, DccSectionOptions defaultSectionOption, List? expandSectionOptions) - => new ConfigurationApiManage(callerFactory.CreateClient(), defaultSectionOption, expandSectionOptions); + => new ConfigurationApiManage(callerProvider, defaultSectionOption, expandSectionOptions); } diff --git a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Masa.Contrib.Configuration.ConfigurationApi.Dcc.csproj b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Masa.Contrib.Configuration.ConfigurationApi.Dcc.csproj index c6e929593..59110779b 100644 --- a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Masa.Contrib.Configuration.ConfigurationApi.Dcc.csproj +++ b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Masa.Contrib.Configuration.ConfigurationApi.Dcc.csproj @@ -9,7 +9,6 @@ - @@ -18,6 +17,8 @@ + + diff --git a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/MasaConfigurationExtensions.cs b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/MasaConfigurationExtensions.cs index 459a99a0d..87d8d1122 100644 --- a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/MasaConfigurationExtensions.cs +++ b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/MasaConfigurationExtensions.cs @@ -58,7 +58,7 @@ public static IMasaConfigurationBuilder UseDcc( DccSectionOptions defaultSectionOptions, List? expansionSectionOptions, Action? jsonSerializerOptions, - Action? callerOptions) + Action? action) { StaticConfig.AppId = defaultSectionOptions.AppId; @@ -75,18 +75,20 @@ public static IMasaConfigurationBuilder UseDcc( PropertyNameCaseInsensitive = true }; jsonSerializerOptions?.Invoke(jsonSerializerOption); + string callerName = DEFAULT_CLIENT_NAME; services.AddCaller(options => { - if (callerOptions == null) + if (action == null) { options.UseHttpClient(() - => new MasaHttpClientBuilder(DEFAULT_CLIENT_NAME, string.Empty, + => new MasaHttpClientBuilder(callerName, string.Empty, opt => opt.BaseAddress = new Uri(config.DccConfigurationOptions.ManageServiceAddress)) ); } else { - callerOptions.Invoke(options); + action.Invoke(options); + callerName = options.Callers.Select(opt => opt.Name).FirstOrDefault(); } }); @@ -94,7 +96,7 @@ public static IMasaConfigurationBuilder UseDcc( .AddSharedMasaMemoryCache(config.DccConfigurationOptions.SubscribeKeyPrefix ?? DEFAULT_SUBSCRIBE_KEY_PREFIX); TryAddConfigurationApiClient(services, config.DefaultSectionOptions, config.ExpansionSectionOptions, jsonSerializerOption); - TryAddConfigurationApiManage(services, config.DefaultSectionOptions, config.ExpansionSectionOptions); + TryAddConfigurationApiManage(services, callerName, config.DefaultSectionOptions, config.ExpansionSectionOptions); var sectionOptions = new List() { @@ -129,13 +131,14 @@ public static IServiceCollection TryAddConfigurationApiClient(IServiceCollection } public static IServiceCollection TryAddConfigurationApiManage(IServiceCollection services, + string callerName, DccSectionOptions defaultSectionOption, List expansionSectionOptions) { services.TryAddSingleton(serviceProvider => { var callerFactory = serviceProvider.GetRequiredService(); - return DccFactory.CreateManage(callerFactory, defaultSectionOption, expansionSectionOptions); + return DccFactory.CreateManage(callerFactory.CreateClient(callerName), defaultSectionOption, expansionSectionOptions); }); return services; } diff --git a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/_Imports.cs b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/_Imports.cs index b31bd6ed3..5219841a2 100644 --- a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/_Imports.cs +++ b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/_Imports.cs @@ -3,19 +3,21 @@ global using Masa.BuildingBlocks.Configuration; global using Masa.BuildingBlocks.Configuration.Options; +global using Masa.BuildingBlocks.Service.Caller; +global using Masa.BuildingBlocks.Service.Caller.Options; global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Internal; global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Internal.Model; global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Internal.Options; global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Internal.Parser; global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Options; +global using Masa.Contrib.Service.Caller; +global using Masa.Contrib.Service.Caller.HttpClient; global using Masa.Utils.Caching.Core.DependencyInjection; global using Masa.Utils.Caching.Core.Models; global using Masa.Utils.Caching.DistributedMemory.DependencyInjection; global using Masa.Utils.Caching.DistributedMemory.Interfaces; global using Masa.Utils.Caching.Redis.Extensions; global using Masa.Utils.Caching.Redis.Models; -global using Masa.Utils.Caller.Core; -global using Masa.Utils.Caller.HttpClient; global using Microsoft.Extensions.Configuration; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.DependencyInjection.Extensions; @@ -25,6 +27,5 @@ global using System.Dynamic; global using System.Text.Json; global using System.Text.Json.Serialization; -global using System.Xml.Linq; global using YamlDotNet.Serialization; global using static Masa.Contrib.Configuration.ConfigurationApi.Dcc.Internal.Constants; diff --git a/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccManageTest.cs b/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccManageTest.cs index abd9f63e9..6f8ce21d9 100644 --- a/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccManageTest.cs +++ b/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccManageTest.cs @@ -1,6 +1,8 @@ // Copyright (c) MASA Stack All rights reserved. // Licensed under the MIT License. See LICENSE.txt in the project root for license information. + + namespace Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests; [TestClass] diff --git a/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccTest.cs b/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccTest.cs index 27c2efa5e..73771f25a 100644 --- a/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccTest.cs +++ b/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccTest.cs @@ -85,8 +85,17 @@ public void TestTryAddConfigurationApiManage() _services.AddSingleton(httpClientFactory.Object); _services.AddCaller(options => options.UseHttpClient()); - MasaConfigurationExtensions.TryAddConfigurationApiManage(_services, new DccSectionOptions(), new List()); - MasaConfigurationExtensions.TryAddConfigurationApiManage(_services, new DccSectionOptions(), new List()); + MasaConfigurationExtensions.TryAddConfigurationApiManage( + _services, + "http", + new DccSectionOptions(), + new List()); + + MasaConfigurationExtensions.TryAddConfigurationApiManage( + _services, + "http", + new DccSectionOptions(), + new List()); Assert.IsTrue(_services.Count(service => service.ServiceType == typeof(IConfigurationApiManage) && service.Lifetime == ServiceLifetime.Singleton) == 1); var serviceProvider = _services.BuildServiceProvider(); diff --git a/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/_Imports.cs b/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/_Imports.cs index 1973c287b..4216f2904 100644 --- a/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/_Imports.cs +++ b/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/_Imports.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. See LICENSE.txt in the project root for license information. global using Masa.BuildingBlocks.Configuration; +global using Masa.BuildingBlocks.Service.Caller; global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Internal; global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Options; global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests.Internal; @@ -9,14 +10,14 @@ global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests.Internal.Config; global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests.Internal.Enum; global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests.Internal.Model; +global using Masa.Contrib.Service.Caller; +global using Masa.Contrib.Service.Caller.HttpClient; global using Masa.Utils.Caching.Core.Interfaces; global using Masa.Utils.Caching.Core.Models; global using Masa.Utils.Caching.DistributedMemory; global using Masa.Utils.Caching.DistributedMemory.Interfaces; global using Masa.Utils.Caching.DistributedMemory.Models; global using Masa.Utils.Caching.Redis.Models; -global using Masa.Utils.Caller.Core; -global using Masa.Utils.Caller.HttpClient; global using Microsoft.AspNetCore.Builder; global using Microsoft.Extensions.Caching.Memory; global using Microsoft.Extensions.Configuration; @@ -24,7 +25,6 @@ global using Microsoft.Extensions.Options; global using Microsoft.VisualStudio.TestTools.UnitTesting; global using Moq; -global using System.Data; global using System.Dynamic; global using System.Net; global using System.Reflection; From 5649cd407d1a1fe0680f5c8127917085a68183d6 Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Tue, 26 Jul 2022 17:51:18 +0800 Subject: [PATCH 03/13] chore: Deprecated IOptionsFactory --- .../Masa.Contrib.Service.Caller/DefaultCallerFactory.cs | 4 ++-- .../Masa.Contrib.Service.Caller/DefaultRequestMessage.cs | 4 ++-- .../Masa.Contrib.Service.Caller/DefaultResponseMessage.cs | 4 ++-- .../Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultCallerFactory.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultCallerFactory.cs index ac621343d..251c826de 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultCallerFactory.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultCallerFactory.cs @@ -8,10 +8,10 @@ internal class DefaultCallerFactory : ICallerFactory private readonly IServiceProvider _serviceProvider; private readonly List _callers; - public DefaultCallerFactory(IServiceProvider serviceProvider, IOptionsFactory callerFactoryOptions) + public DefaultCallerFactory(IServiceProvider serviceProvider, IOptions options) { _serviceProvider = serviceProvider; - _callers = callerFactoryOptions.Create(Options.DefaultName).Callers; + _callers = options.Value.Callers; } public ICallerProvider CreateClient() diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs index 2b2c9ff33..cddcf7233 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs @@ -10,13 +10,13 @@ public abstract class DefaultRequestMessage private readonly IHttpContextAccessor? _httpContextAccessor; protected readonly CallerFactoryOptions Options; - public DefaultRequestMessage(IOptionsFactory optionsFactory, + public DefaultRequestMessage(IOptions options, IRequestIdGenerator requestIdGenerator, IHttpContextAccessor? httpContextAccessor = null) { _requestIdGenerator = requestIdGenerator; _httpContextAccessor = httpContextAccessor; - Options = optionsFactory.Create(Microsoft.Extensions.Options.Options.DefaultName); + Options = options.Value; _requestIdKey = Options.RequestIdKey ?? "Masa-Request-Id"; } diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultResponseMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultResponseMessage.cs index 45b360cc6..904125f57 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultResponseMessage.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultResponseMessage.cs @@ -8,9 +8,9 @@ public class DefaultResponseMessage : IResponseMessage private readonly ILogger? _logger; private readonly CallerFactoryOptions _options; - public DefaultResponseMessage(IOptionsFactory optionsFactory, ILogger? logger = null) + public DefaultResponseMessage(IOptions options, ILogger? logger = null) { - _options = optionsFactory.Create(Options.DefaultName); + _options = options.Value; _logger = logger; } diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs index cb1e96365..4a7cbf749 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs @@ -8,10 +8,10 @@ public class JsonRequestMessage : DefaultRequestMessage, IRequestMessage private readonly JsonSerializerOptions? _jsonSerializerOptions; public JsonRequestMessage( - IOptionsFactory optionsFactory, + IOptions options, IRequestIdGenerator requestIdGenerator, IHttpContextAccessor? httpContextAccessor = null) - : base(optionsFactory, requestIdGenerator, httpContextAccessor) + : base(options, requestIdGenerator, httpContextAccessor) { _jsonSerializerOptions = Options.JsonSerializerOptions; } From cad1a5670836235e4a457d1790377af836935c02 Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Thu, 28 Jul 2022 14:59:24 +0800 Subject: [PATCH 04/13] feat(Caller.Dapr): Support custom HTTPRequestMessage --- .../CallerOptionsExtensions.cs | 6 +++--- .../DefaultRequestMessage.cs | 2 +- .../CallerTest.cs | 3 --- .../Callers/UserDaprCallerBase.cs | 9 --------- .../DefaultDaprRequestMessage.cs | 13 +++++++++++++ .../_Imports.cs | 2 ++ 6 files changed, 19 insertions(+), 16 deletions(-) create mode 100644 test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/DefaultDaprRequestMessage.cs diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/CallerOptionsExtensions.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/CallerOptionsExtensions.cs index 783ffc0bb..14ae3224c 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/CallerOptionsExtensions.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/CallerOptionsExtensions.cs @@ -5,7 +5,7 @@ namespace Masa.Contrib.Service.Caller.DaprClient; public static class CallerOptionsExtensions { - public static CallerOptions UseDapr(this CallerOptions callerOptions, Func clientBuilder) + public static DefaultDaprClientBuilder UseDapr(this CallerOptions callerOptions, Func clientBuilder) { if (clientBuilder == null) throw new ArgumentNullException(nameof(clientBuilder)); @@ -24,10 +24,10 @@ public static CallerOptions UseDapr(this CallerOptions callerOptions, Func new DaprCallerProvider(serviceProvider, builder.Name, builder.AppId)); - return callerOptions; + return new DefaultDaprClientBuilder(callerOptions.Services, builder.Name); } - public static CallerOptions UseDapr(this CallerOptions callerOptions, Action clientBuilder) + public static DefaultDaprClientBuilder UseDapr(this CallerOptions callerOptions, Action clientBuilder) { if (clientBuilder == null) throw new ArgumentNullException(nameof(clientBuilder)); diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs index cddcf7233..70a36d50c 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs @@ -20,7 +20,7 @@ public DefaultRequestMessage(IOptions options, _requestIdKey = Options.RequestIdKey ?? "Masa-Request-Id"; } - protected void TrySetRequestId(HttpRequestMessage requestMessage) + protected virtual void TrySetRequestId(HttpRequestMessage requestMessage) { var httpContext = _httpContextAccessor?.HttpContext; if (httpContext == null) diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/CallerTest.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/CallerTest.cs index e38262ea1..892278925 100644 --- a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/CallerTest.cs +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/CallerTest.cs @@ -1,9 +1,6 @@ // Copyright (c) MASA Stack All rights reserved. // Licensed under the MIT License. See LICENSE.txt in the project root for license information. -using Masa.BuildingBlocks.Service.Caller.Options; -using Microsoft.Extensions.Options; - namespace Masa.Contrib.Service.Caller.AutomaticCaller.Tests; [TestClass] diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/UserDaprCallerBase.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/UserDaprCallerBase.cs index de2b5eb55..9bb72570a 100644 --- a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/UserDaprCallerBase.cs +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/UserDaprCallerBase.cs @@ -18,12 +18,3 @@ protected override DefaultDaprClientBuilder UseDapr() return base.UseDapr().AddHttpRequestMessage(); } } - -public class DefaultDaprRequestMessage : IDaprRequestMessage -{ - public Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage) - { - requestMessage.Headers.Add("test", "test"); - return Task.FromResult(requestMessage); - } -} diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/DefaultDaprRequestMessage.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/DefaultDaprRequestMessage.cs new file mode 100644 index 000000000..256586aa2 --- /dev/null +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/DefaultDaprRequestMessage.cs @@ -0,0 +1,13 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.AutomaticCaller.Tests; + +public class DefaultDaprRequestMessage : IDaprRequestMessage +{ + public Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage) + { + requestMessage.Headers.Add("test", "test"); + return Task.FromResult(requestMessage); + } +} diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/_Imports.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/_Imports.cs index bb4252613..58e77bd7b 100644 --- a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/_Imports.cs +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/_Imports.cs @@ -2,10 +2,12 @@ // Licensed under the MIT License. See LICENSE.txt in the project root for license information. global using Masa.BuildingBlocks.Service.Caller; +global using Masa.BuildingBlocks.Service.Caller.Options; global using Masa.Contrib.Service.Caller.AutomaticCaller.Tests.Callers; global using Masa.Contrib.Service.Caller.DaprClient; global using Masa.Contrib.Service.Caller.HttpClient; global using Microsoft.AspNetCore.Builder; global using Microsoft.Extensions.DependencyInjection; +global using Microsoft.Extensions.Options; global using Microsoft.VisualStudio.TestTools.UnitTesting; global using System.Net; From d7047efae7a552ae12ba032566686357597b88ed Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Thu, 28 Jul 2022 16:32:51 +0800 Subject: [PATCH 05/13] docs: Modify Caller Document --- src/BuildingBlocks/MASA.BuildingBlocks | 2 +- .../Caller/Masa.Contrib.Service.Caller.DaprClient/README.md | 1 + .../Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md | 1 + .../Caller/Masa.Contrib.Service.Caller.HttpClient/README.md | 1 + .../Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md | 1 + 5 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/BuildingBlocks/MASA.BuildingBlocks b/src/BuildingBlocks/MASA.BuildingBlocks index aac974647..869794569 160000 --- a/src/BuildingBlocks/MASA.BuildingBlocks +++ b/src/BuildingBlocks/MASA.BuildingBlocks @@ -1 +1 @@ -Subproject commit aac9746472bbdf191f7cb2918dabd6f08cd561bc +Subproject commit 869794569eb140e5bbc208ee02b14e22c90cf8f6 diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.md b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.md index 76b92be37..87eddde43 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.md +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.md @@ -5,6 +5,7 @@ ## Example: ````c# +Install-Package Masa.Contrib.Service.Caller Install-Package Masa.Contrib.Service.Caller.DaprClient ```` diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md index 242b3e93c..8b28e8f90 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md @@ -5,6 +5,7 @@ ## 用例: ```c# +Install-Package Masa.Contrib.Service.Caller Install-Package Masa.Contrib.Service.Caller.DaprClient ``` diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.md b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.md index 98b9c0b6c..1958c306c 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.md +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.md @@ -5,6 +5,7 @@ ## Example: ````c# +Install-Package Masa.Contrib.Service.Caller Install-Package Masa.Contrib.Service.Caller.HttpClient ```` diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md index 9b978b6cb..8d927cc12 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md @@ -5,6 +5,7 @@ ## 用例: ```c# +Install-Package Masa.Contrib.Service.Caller Install-Package Masa.Contrib.Service.Caller.HttpClient ``` From 3ae76449390af72a3dca8d3d53770a2e813afa3a Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Thu, 28 Jul 2022 17:20:36 +0800 Subject: [PATCH 06/13] feat(Caller): Replaced with Contrib.Caller --- Masa.Contrib.sln | 31 ++++++++++--------- .../Masa.Contrib.BasicAbility.Auth.csproj | 3 +- .../ServiceCollectionExtensions.cs | 4 +-- .../_Imports.cs | 6 ++-- .../Masa.Contrib.BasicAbility.Mc.csproj | 6 ++-- .../Masa.Contrib.BasicAbility.Mc/_Imports.cs | 14 +++++---- .../Masa.Contrib.BasicAbility.Pm.csproj | 3 +- .../Masa.Contrib.BasicAbility.Pm/_Imports.cs | 6 ++-- ...Masa.Contrib.BasicAbility.Scheduler.csproj | 6 ++-- .../_Imports.cs | 11 ++++--- .../Extensions/CallerProviderExtensions.cs | 2 +- .../Masa.Contrib.BasicAbility.Tsc.csproj | 4 +-- .../Masa.Contrib.BasicAbility.Tsc/_Imports.cs | 7 +++-- .../Masa.Contrib.Service.Caller/README.md | 4 +-- .../README.zh-CN.md | 4 +-- .../_Imports.cs | 2 +- .../_Imports.cs | 2 +- .../_Imports.cs | 4 +-- .../_Imports.cs | 4 +-- .../_Imports.cs | 3 +- 20 files changed, 69 insertions(+), 57 deletions(-) diff --git a/Masa.Contrib.sln b/Masa.Contrib.sln index b040bb3fe..7c2b111b4 100644 --- a/Masa.Contrib.sln +++ b/Masa.Contrib.sln @@ -324,21 +324,23 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.BasicAbility.T EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.BasicAbility.Tsc", "src\BuildingBlocks\MASA.BuildingBlocks\src\BasicAbility\Masa.BuildingBlocks.BasicAbility.Tsc\Masa.BuildingBlocks.BasicAbility.Tsc.csproj", "{C265268A-F311-4B6A-915E-C1AF9D1EB624}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.BuildingBlocks.Service.Caller", "src\BuildingBlocks\MASA.BuildingBlocks\src\Service\Masa.BuildingBlocks.Service.Caller\Masa.BuildingBlocks.Service.Caller.csproj", "{ABF6E41A-CBF9-49DE-87FC-9D88F440A104}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.Service.Caller", "src\BuildingBlocks\MASA.BuildingBlocks\src\Service\Masa.BuildingBlocks.Service.Caller\Masa.BuildingBlocks.Service.Caller.csproj", "{ABF6E41A-CBF9-49DE-87FC-9D88F440A104}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Caller", "Caller", "{F9DDEB6F-25F8-4505-8300-2E247564BD8B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.Service.Caller.DaprClient", "src\Service\Caller\Masa.Contrib.Service.Caller.DaprClient\Masa.Contrib.Service.Caller.DaprClient.csproj", "{1CDA9001-A29F-4EBE-BBEA-0B2E663B9A19}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Service.Caller.DaprClient", "src\Service\Caller\Masa.Contrib.Service.Caller.DaprClient\Masa.Contrib.Service.Caller.DaprClient.csproj", "{1CDA9001-A29F-4EBE-BBEA-0B2E663B9A19}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.Service.Caller.HttpClient", "src\Service\Caller\Masa.Contrib.Service.Caller.HttpClient\Masa.Contrib.Service.Caller.HttpClient.csproj", "{00659C82-2E23-4E8F-BA34-EC41D78C87A1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Service.Caller.HttpClient", "src\Service\Caller\Masa.Contrib.Service.Caller.HttpClient\Masa.Contrib.Service.Caller.HttpClient.csproj", "{00659C82-2E23-4E8F-BA34-EC41D78C87A1}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.Service.Caller", "src\Service\Caller\Masa.Contrib.Service.Caller\Masa.Contrib.Service.Caller.csproj", "{28893415-0789-4FBB-A8B7-F0F9260CEDE3}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Service.Caller", "src\Service\Caller\Masa.Contrib.Service.Caller\Masa.Contrib.Service.Caller.csproj", "{28893415-0789-4FBB-A8B7-F0F9260CEDE3}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Service", "Service", "{4AA6B450-D4AA-4474-9ECF-52A44935D8D9}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.Service.Caller.Tests", "test\Masa.Contrib.Service.Caller.Tests\Masa.Contrib.Service.Caller.Tests.csproj", "{D855894E-4C72-41DC-8F84-EF66CDE37453}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Service.Caller.Tests", "test\Masa.Contrib.Service.Caller.Tests\Masa.Contrib.Service.Caller.Tests.csproj", "{D855894E-4C72-41DC-8F84-EF66CDE37453}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.Service.Caller.AutomaticCaller.Tests", "test\Masa.Contrib.Service.Caller.AutomaticCaller.Tests\Masa.Contrib.Service.Caller.AutomaticCaller.Tests.csproj", "{1EE45374-EF8E-4E9D-A74F-51C14DA58ED8}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Service.Caller.AutomaticCaller.Tests", "test\Masa.Contrib.Service.Caller.AutomaticCaller.Tests\Masa.Contrib.Service.Caller.AutomaticCaller.Tests.csproj", "{1EE45374-EF8E-4E9D-A74F-51C14DA58ED8}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "BasicAbility", "BasicAbility", "{7012AE14-D352-405F-8412-4B60A017AEC9}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -1464,6 +1466,7 @@ Global {428CDAF3-957A-4017-82EA-70737F205546} = {38E6C400-90C0-493E-9266-C1602E229F1B} {DB93B639-899D-4B2C-AF8A-47B4BC6B3776} = {9EEE31DA-3165-4CB3-AAE9-27CC3A4DE669} {9EEE31DA-3165-4CB3-AAE9-27CC3A4DE669} = {38E6C400-90C0-493E-9266-C1602E229F1B} + {A5C1EF6B-A3B5-4D0C-8373-F854EE7EF4AD} = {4AA6B450-D4AA-4474-9ECF-52A44935D8D9} {B29ABF5D-AFA8-4480-B74E-3ACB6FAAA826} = {13EDB361-AF88-4F89-B4AB-46622BCCBC37} {5A163042-B03A-4063-85FF-22D4C5BB5B90} = {38E6C400-90C0-493E-9266-C1602E229F1B} {84EFF9E1-6852-458F-8D57-62E3F084EA0F} = {9EEE31DA-3165-4CB3-AAE9-27CC3A4DE669} @@ -1496,7 +1499,6 @@ Global {118A91A6-6FBB-431A-B50D-076375AD6A63} = {5DFAF4A2-ECB5-46E4-904D-1EA5F48B2D48} {74283F68-6B38-4CF4-B0CB-AAD65618ADB8} = {DC578D74-98F0-4F19-A230-CFA8DAEE0AF1} {AB6FAB84-5218-48A8-8F94-03B02ECD098F} = {0D34A7F0-DC77-4789-A136-93089CBD15C3} - {C4DDEA6E-D6AF-4890-9713-C2862403E57C} = {38E6C400-90C0-493E-9266-C1602E229F1B} {86898E0C-D1C5-4A57-B5DD-69A4BC1F4ABE} = {165391A5-034E-4894-8084-8DF7D4AA7518} {97532A33-A591-4DF5-A2C0-72527B78ED82} = {38E6C400-90C0-493E-9266-C1602E229F1B} {165391A5-034E-4894-8084-8DF7D4AA7518} = {42DF7AAC-362C-48F4-B76A-BDEEEFF17CC9} @@ -1525,7 +1527,6 @@ Global {CE1CABB0-B307-4709-84E0-583382FAAA29} = {5DFAF4A2-ECB5-46E4-904D-1EA5F48B2D48} {E7987CBB-8DDD-4AC5-B522-653E2F457C85} = {6DB8780E-BA11-47CD-8FAB-D73A1F71B305} {AD427256-9686-4289-A635-1B387BD56D15} = {E6363F59-2BA4-4AA7-8578-C433A2C2567F} - {2B644A8C-F0EE-4566-AB78-9E1C6D4185A3} = {38E6C400-90C0-493E-9266-C1602E229F1B} {4995742C-033A-4147-89E7-7FFE7681C971} = {42DF7AAC-362C-48F4-B76A-BDEEEFF17CC9} {B7F5651E-C4CB-413E-AF6E-420D1AFB7EA6} = {DC578D74-98F0-4F19-A230-CFA8DAEE0AF1} {DC50078D-D706-4CB9-A301-F47CB3F46007} = {6DB8780E-BA11-47CD-8FAB-D73A1F71B305} @@ -1557,27 +1558,24 @@ Global {AA7876FF-3EF9-40EC-B5FF-66AB748DB93E} = {5F25960E-646D-4EA6-A648-3CAD284B6E38} {DB2B4DA3-EEF2-49AA-93A4-B00C25210A68} = {38E6C400-90C0-493E-9266-C1602E229F1B} {23582B50-BAEA-4A2D-82A4-345A3C30124E} = {59DA3D5F-9E39-4173-8C31-126967CC189F} + {1371F22B-FDD7-43B0-8E7D-E68DA31F07F3} = {9EEE31DA-3165-4CB3-AAE9-27CC3A4DE669} {FF3FD53D-D23E-48AC-98B6-3B028B4DE8AF} = {0D34A7F0-DC77-4789-A136-93089CBD15C3} {83FA668F-C838-4883-996D-AF2ECF00FDF8} = {5DFAF4A2-ECB5-46E4-904D-1EA5F48B2D48} - {789ABED5-7C94-4F6F-ADCA-E97F3DFC9479} = {38E6C400-90C0-493E-9266-C1602E229F1B} {981E883E-CCDC-400B-8FB1-76E1E65C32AF} = {0D34A7F0-DC77-4789-A136-93089CBD15C3} {0D34A7F0-DC77-4789-A136-93089CBD15C3} = {DC578D74-98F0-4F19-A230-CFA8DAEE0AF1} {0EB0CB69-4C44-4462-A92A-A9B9FDA171DE} = {0D34A7F0-DC77-4789-A136-93089CBD15C3} - {5980D054-E2F3-4143-93D1-01993A955AE7} = {38E6C400-90C0-493E-9266-C1602E229F1B} {8D84666E-C79E-4D49-B73D-360E62D312EF} = {5DFAF4A2-ECB5-46E4-904D-1EA5F48B2D48} {7C4B88FA-3681-4C29-BC3F-0FDB111C5681} = {FBD326D3-E59C-433E-A88E-14E179E3093D} {592297DE-DA72-452D-9D88-61EE882FE9A6} = {38E6C400-90C0-493E-9266-C1602E229F1B} {4E237346-F948-46AC-801B-492545978280} = {38E6C400-90C0-493E-9266-C1602E229F1B} {75A25CF6-9BA4-46F5-8BC3-90396230CB64} = {5DFAF4A2-ECB5-46E4-904D-1EA5F48B2D48} {DA816A33-F164-4456-92DD-A672BAD1A6B1} = {0D34A7F0-DC77-4789-A136-93089CBD15C3} - {23633E49-F11A-4D14-899A-E2599C8182CE} = {38E6C400-90C0-493E-9266-C1602E229F1B} {FC4E526A-DBFC-406A-8ED3-64983B67F688} = {E33ADF54-4D35-49B7-BDA6-412587CA39FF} {AE3607C0-3278-46D7-97CD-4E6F37C120D3} = {07BD7788-9DC0-4BD0-9861-0C9AC13B4EB8} {A1232A01-3927-4EDE-B7D4-657E08DEB36D} = {07BD7788-9DC0-4BD0-9861-0C9AC13B4EB8} {2870B6BB-4188-45A0-A2D3-085834EBDC2A} = {DB2B4DA3-EEF2-49AA-93A4-B00C25210A68} {913DA066-8A23-4671-AC8F-B5B61134F8FE} = {DB2B4DA3-EEF2-49AA-93A4-B00C25210A68} {4CD3D849-7277-4C9C-9461-7ABB66F78629} = {38E6C400-90C0-493E-9266-C1602E229F1B} - {FED315CF-7CA2-4653-AD37-BC0C1D7FFD22} = {38E6C400-90C0-493E-9266-C1602E229F1B} {C265268A-F311-4B6A-915E-C1AF9D1EB624} = {0D34A7F0-DC77-4789-A136-93089CBD15C3} {ABF6E41A-CBF9-49DE-87FC-9D88F440A104} = {DC578D74-98F0-4F19-A230-CFA8DAEE0AF1} {F9DDEB6F-25F8-4505-8300-2E247564BD8B} = {593A3114-D1E0-47ED-BC37-58E08886175B} @@ -1585,10 +1583,15 @@ Global {00659C82-2E23-4E8F-BA34-EC41D78C87A1} = {F9DDEB6F-25F8-4505-8300-2E247564BD8B} {28893415-0789-4FBB-A8B7-F0F9260CEDE3} = {F9DDEB6F-25F8-4505-8300-2E247564BD8B} {4AA6B450-D4AA-4474-9ECF-52A44935D8D9} = {38E6C400-90C0-493E-9266-C1602E229F1B} - {A5C1EF6B-A3B5-4D0C-8373-F854EE7EF4AD} = {4AA6B450-D4AA-4474-9ECF-52A44935D8D9} {D855894E-4C72-41DC-8F84-EF66CDE37453} = {4AA6B450-D4AA-4474-9ECF-52A44935D8D9} {1EE45374-EF8E-4E9D-A74F-51C14DA58ED8} = {4AA6B450-D4AA-4474-9ECF-52A44935D8D9} - {1371F22B-FDD7-43B0-8E7D-E68DA31F07F3} = {9EEE31DA-3165-4CB3-AAE9-27CC3A4DE669} + {7012AE14-D352-405F-8412-4B60A017AEC9} = {38E6C400-90C0-493E-9266-C1602E229F1B} + {2B644A8C-F0EE-4566-AB78-9E1C6D4185A3} = {7012AE14-D352-405F-8412-4B60A017AEC9} + {789ABED5-7C94-4F6F-ADCA-E97F3DFC9479} = {7012AE14-D352-405F-8412-4B60A017AEC9} + {23633E49-F11A-4D14-899A-E2599C8182CE} = {7012AE14-D352-405F-8412-4B60A017AEC9} + {C4DDEA6E-D6AF-4890-9713-C2862403E57C} = {7012AE14-D352-405F-8412-4B60A017AEC9} + {5980D054-E2F3-4143-93D1-01993A955AE7} = {7012AE14-D352-405F-8412-4B60A017AEC9} + {FED315CF-7CA2-4653-AD37-BC0C1D7FFD22} = {7012AE14-D352-405F-8412-4B60A017AEC9} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {40383055-CC50-4600-AD9A-53C14F620D03} diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Masa.Contrib.BasicAbility.Auth.csproj b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Masa.Contrib.BasicAbility.Auth.csproj index 68cab7db7..dc927aa13 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Masa.Contrib.BasicAbility.Auth.csproj +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Masa.Contrib.BasicAbility.Auth.csproj @@ -7,7 +7,6 @@ - @@ -16,6 +15,8 @@ + + diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/ServiceCollectionExtensions.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/ServiceCollectionExtensions.cs index 7d0be76bb..538e8bb2a 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/ServiceCollectionExtensions.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/ServiceCollectionExtensions.cs @@ -22,10 +22,8 @@ public static IServiceCollection AddAuthClient(this IServiceCollection services, { ArgumentNullException.ThrowIfNull(callerOptions, nameof(callerOptions)); - if (!services.Any(service => service.ServiceType == typeof(IMultiEnvironmentUserContext))) - { + if (services.All(service => service.ServiceType != typeof(IMultiEnvironmentUserContext))) throw new Exception("Please add IMultiEnvironmentUserContext first."); - } services.AddHttpContextAccessor(); services.AddScoped(); diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/_Imports.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/_Imports.cs index 30b3b0927..54a7e4cf0 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/_Imports.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/_Imports.cs @@ -5,10 +5,12 @@ global using Masa.BuildingBlocks.BasicAbility.Auth.Contracts.Model; global using Masa.BuildingBlocks.BasicAbility.Auth.Service; global using Masa.BuildingBlocks.Identity.IdentityModel; +global using Masa.BuildingBlocks.Service.Caller; +global using Masa.BuildingBlocks.Service.Caller.Options; global using Masa.Contrib.BasicAbility.Auth; global using Masa.Contrib.BasicAbility.Auth.Service; -global using Masa.Utils.Caller.Core; -global using Masa.Utils.Caller.HttpClient; +global using Masa.Contrib.Service.Caller; +global using Masa.Contrib.Service.Caller.HttpClient; global using Microsoft.AspNetCore.Http; global using System.Text.Json; global using static Masa.Contrib.BasicAbility.Auth.Constants; diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Masa.Contrib.BasicAbility.Mc.csproj b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Masa.Contrib.BasicAbility.Mc.csproj index dc5193a50..add5246c8 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Masa.Contrib.BasicAbility.Mc.csproj +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Masa.Contrib.BasicAbility.Mc.csproj @@ -6,12 +6,10 @@ enable - - - - + + diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/_Imports.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/_Imports.cs index c4d610029..c0ad44a6c 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/_Imports.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/_Imports.cs @@ -2,17 +2,19 @@ // Licensed under the MIT License. See LICENSE.txt in the project root for license information. global using Masa.BuildingBlocks.BasicAbility.Mc; -global using Masa.BuildingBlocks.BasicAbility.Mc.Service; global using Masa.BuildingBlocks.BasicAbility.Mc.Model; +global using Masa.BuildingBlocks.BasicAbility.Mc.Service; +global using Masa.BuildingBlocks.Service.Caller; +global using Masa.BuildingBlocks.Service.Caller.Options; global using Masa.Contrib.BasicAbility.Mc; -global using static Masa.Contrib.BasicAbility.Mc.Constants; global using Masa.Contrib.BasicAbility.Mc.Infrastructure.Helper; global using Masa.Contrib.BasicAbility.Mc.Service; -global using Masa.Utils.Caller.Core; -global using Masa.Utils.Caller.HttpClient; +global using Masa.Contrib.Service.Caller; +global using Masa.Contrib.Service.Caller.HttpClient; +global using Microsoft.AspNetCore.Authentication; +global using Microsoft.AspNetCore.Http; global using System.ComponentModel; global using System.Diagnostics.CodeAnalysis; global using System.Globalization; global using System.Reflection; -global using Microsoft.AspNetCore.Http; -global using Microsoft.AspNetCore.Authentication; +global using static Masa.Contrib.BasicAbility.Mc.Constants; diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Masa.Contrib.BasicAbility.Pm.csproj b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Masa.Contrib.BasicAbility.Pm.csproj index b38dc0579..02f84d061 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Masa.Contrib.BasicAbility.Pm.csproj +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Masa.Contrib.BasicAbility.Pm.csproj @@ -9,12 +9,13 @@ - + + diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/_Imports.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/_Imports.cs index ed19af931..c8397c3a4 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/_Imports.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/_Imports.cs @@ -4,8 +4,10 @@ global using Masa.BuildingBlocks.BasicAbility.Pm; global using Masa.BuildingBlocks.BasicAbility.Pm.Model; global using Masa.BuildingBlocks.BasicAbility.Pm.Service; +global using Masa.BuildingBlocks.Service.Caller; +global using Masa.BuildingBlocks.Service.Caller.Options; global using Masa.Contrib.BasicAbility.Pm; global using Masa.Contrib.BasicAbility.Pm.Service; -global using Masa.Utils.Caller.Core; -global using Masa.Utils.Caller.HttpClient; +global using Masa.Contrib.Service.Caller; +global using Masa.Contrib.Service.Caller.HttpClient; global using static Masa.Contrib.BasicAbility.Pm.Constants; diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/Masa.Contrib.BasicAbility.Scheduler.csproj b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/Masa.Contrib.BasicAbility.Scheduler.csproj index 013e83a80..eac78816a 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/Masa.Contrib.BasicAbility.Scheduler.csproj +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/Masa.Contrib.BasicAbility.Scheduler.csproj @@ -7,12 +7,14 @@ - + - + + + diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/_Imports.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/_Imports.cs index f8e2f2715..9dddd3d09 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/_Imports.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/_Imports.cs @@ -4,12 +4,13 @@ global using Masa.BuildingBlocks.BasicAbility.Scheduler; global using Masa.BuildingBlocks.BasicAbility.Scheduler.Request; global using Masa.BuildingBlocks.BasicAbility.Scheduler.Service; -global using Masa.BuildingBlocks.Identity.IdentityModel; +global using Masa.BuildingBlocks.Service.Caller; +global using Masa.BuildingBlocks.Service.Caller.Options; global using Masa.Contrib.BasicAbility.Scheduler; global using Masa.Contrib.BasicAbility.Scheduler.Services; -global using Masa.Utils.Caller.Core; -global using Masa.Utils.Caller.HttpClient; -global using Microsoft.Extensions.Logging; -global using static Masa.Contrib.BasicAbility.Scheduler.Constants; +global using Masa.Contrib.Service.Caller; +global using Masa.Contrib.Service.Caller.HttpClient; global using Microsoft.AspNetCore.Authentication; global using Microsoft.AspNetCore.Http; +global using Microsoft.Extensions.Logging; +global using static Masa.Contrib.BasicAbility.Scheduler.Constants; diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Extensions/CallerProviderExtensions.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Extensions/CallerProviderExtensions.cs index ea44b36bd..1078d7435 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Extensions/CallerProviderExtensions.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Extensions/CallerProviderExtensions.cs @@ -2,7 +2,7 @@ // Licensed under the MIT License. See LICENSE.txt in the project root for license information. [assembly: InternalsVisibleTo("Masa.Contrib.BasicAbility.Tsc.Tests")] -namespace Masa.Utils.Caller.Core; +namespace Masa.Contrib.Service.Caller; internal static class CallerProviderExtensions { diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Masa.Contrib.BasicAbility.Tsc.csproj b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Masa.Contrib.BasicAbility.Tsc.csproj index cf843b888..2bfccdb18 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Masa.Contrib.BasicAbility.Tsc.csproj +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Masa.Contrib.BasicAbility.Tsc.csproj @@ -7,8 +7,6 @@ - - @@ -23,6 +21,8 @@ + + diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/_Imports.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/_Imports.cs index cbb809b1e..47fc6c8c6 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/_Imports.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/_Imports.cs @@ -1,13 +1,14 @@ // Copyright (c) MASA Stack All rights reserved. -// Licensed under the Apache License. See LICENSE.txt in the project root for license information. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. global using Masa.BuildingBlocks.BasicAbility.Tsc; global using Masa.BuildingBlocks.BasicAbility.Tsc.Model; global using Masa.BuildingBlocks.BasicAbility.Tsc.Service; +global using Masa.BuildingBlocks.Service.Caller; global using Masa.Contrib.BasicAbility.Tsc; global using Masa.Contrib.BasicAbility.Tsc.Service; -global using Masa.Utils.Caller.Core; -global using Masa.Utils.Caller.HttpClient; +global using Masa.Contrib.Service.Caller; +global using Masa.Contrib.Service.Caller.HttpClient; global using Microsoft.AspNetCore.Http; global using Microsoft.Extensions.DependencyInjection; global using OpenTelemetry.Contrib.Instrumentation.ElasticsearchClient; diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/README.md b/src/Service/Caller/Masa.Contrib.Service.Caller/README.md index a5988e2a5..1c986b0c2 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/README.md +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/README.md @@ -14,8 +14,8 @@ Masa.Contrib.Service.Caller is the basic class library of Caller, which provides `Masa.Contrib.Service.Caller` is the basic class library of Caller, but it cannot be used alone. Currently, Caller supports two implementations: -* Implementation based on HttpClient: [Masa.Utils.Caller.HttpClient](../Masa.Utils.Caller.HttpClient/README.md) -* Implementation based on DaprClient: [Masa.Utils.Caller.DaprClient](../Masa.Utils.Caller.DaprClient/README.md) +* Implementation based on HttpClient: [Masa.Contrib.Service.Caller.HttpClient](../Masa.Contrib.Service.Caller.HttpClient/README.md) +* Implementation based on DaprClient: [Masa.Contrib.Service.Caller.DaprClient](../Masa.Contrib.Service.Caller.DaprClient/README.md) > Q: What should I do if the callee uses xml instead of json? > diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/README.zh-CN.md b/src/Service/Caller/Masa.Contrib.Service.Caller/README.zh-CN.md index 72c9a4411..c90e74f30 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/README.zh-CN.md +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/README.zh-CN.md @@ -14,8 +14,8 @@ Masa.Contrib.Service.Caller是Caller的基础类库,提供了以下能力的 `Masa.Contrib.Service.Caller`是Caller的基础类库,但不能单独使用,目前Caller支持了两种实现方式: -* 基于HttpClient的实现: [Masa.Utils.Caller.HttpClient](../Masa.Utils.Caller.HttpClient/README.zh-CN.md) -* 基于DaprClient的实现: [Masa.Utils.Caller.DaprClient](../Masa.Utils.Caller.DaprClient/README.zh-CN.md) +* 基于HttpClient的实现: [Masa.Contrib.Service.Caller.HttpClient](../Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md) +* 基于DaprClient的实现: [Masa.Contrib.Service.Caller.DaprClient](../Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md) > Q: 如果被调用方使用的是数据格式为xml,而不是json,我应该怎么做? > diff --git a/test/Masa.Contrib.BasicAbility.Auth.Tests/_Imports.cs b/test/Masa.Contrib.BasicAbility.Auth.Tests/_Imports.cs index a75dc79d9..336ffec61 100644 --- a/test/Masa.Contrib.BasicAbility.Auth.Tests/_Imports.cs +++ b/test/Masa.Contrib.BasicAbility.Auth.Tests/_Imports.cs @@ -5,8 +5,8 @@ global using Masa.BuildingBlocks.BasicAbility.Auth.Contracts.Enum; global using Masa.BuildingBlocks.BasicAbility.Auth.Contracts.Model; global using Masa.BuildingBlocks.Identity.IdentityModel; +global using Masa.BuildingBlocks.Service.Caller; global using Masa.Contrib.BasicAbility.Auth.Service; -global using Masa.Utils.Caller.Core; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.VisualStudio.TestTools.UnitTesting; global using Moq; diff --git a/test/Masa.Contrib.BasicAbility.Mc.Tests/_Imports.cs b/test/Masa.Contrib.BasicAbility.Mc.Tests/_Imports.cs index 5c67a69dd..4e8fbcf04 100644 --- a/test/Masa.Contrib.BasicAbility.Mc.Tests/_Imports.cs +++ b/test/Masa.Contrib.BasicAbility.Mc.Tests/_Imports.cs @@ -3,8 +3,8 @@ global using Masa.BuildingBlocks.BasicAbility.Mc; global using Masa.BuildingBlocks.BasicAbility.Mc.Model; +global using Masa.BuildingBlocks.Service.Caller; global using Masa.Contrib.BasicAbility.Mc.Service; -global using Masa.Utils.Caller.Core; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.VisualStudio.TestTools.UnitTesting; global using Moq; diff --git a/test/Masa.Contrib.BasicAbility.Pm.Tests/_Imports.cs b/test/Masa.Contrib.BasicAbility.Pm.Tests/_Imports.cs index 6250eedd8..8b19b361e 100644 --- a/test/Masa.Contrib.BasicAbility.Pm.Tests/_Imports.cs +++ b/test/Masa.Contrib.BasicAbility.Pm.Tests/_Imports.cs @@ -3,8 +3,8 @@ global using Masa.BuildingBlocks.BasicAbility.Pm; global using Masa.BuildingBlocks.BasicAbility.Pm.Model; -global using Masa.Utils.Caller.Core; -global using Masa.Utils.Caller.HttpClient; +global using Masa.BuildingBlocks.Service.Caller; +global using Masa.Contrib.Service.Caller.HttpClient; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.VisualStudio.TestTools.UnitTesting; global using Moq; diff --git a/test/Masa.Contrib.BasicAbility.Scheduler.Tests/_Imports.cs b/test/Masa.Contrib.BasicAbility.Scheduler.Tests/_Imports.cs index a2ca75efd..9819249f7 100644 --- a/test/Masa.Contrib.BasicAbility.Scheduler.Tests/_Imports.cs +++ b/test/Masa.Contrib.BasicAbility.Scheduler.Tests/_Imports.cs @@ -5,8 +5,8 @@ global using Masa.BuildingBlocks.BasicAbility.Scheduler.Enum; global using Masa.BuildingBlocks.BasicAbility.Scheduler.Model; global using Masa.BuildingBlocks.BasicAbility.Scheduler.Request; -global using Masa.Utils.Caller.Core; -global using Masa.Utils.Caller.HttpClient; +global using Masa.BuildingBlocks.Service.Caller; +global using Masa.Contrib.Service.Caller.HttpClient; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.Logging; global using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/test/Masa.Contrib.BasicAbility.Tsc.Test/_Imports.cs b/test/Masa.Contrib.BasicAbility.Tsc.Test/_Imports.cs index 88e3b09ee..ca1068508 100644 --- a/test/Masa.Contrib.BasicAbility.Tsc.Test/_Imports.cs +++ b/test/Masa.Contrib.BasicAbility.Tsc.Test/_Imports.cs @@ -3,8 +3,9 @@ global using Masa.BuildingBlocks.BasicAbility.Tsc.Enums; global using Masa.BuildingBlocks.BasicAbility.Tsc.Model; +global using Masa.BuildingBlocks.Service.Caller; global using Masa.Contrib.BasicAbility.Tsc.Service; -global using Masa.Utils.Caller.Core; +global using Masa.Contrib.Service.Caller; global using Microsoft.VisualStudio.TestTools.UnitTesting; global using Moq; global using System; From 61ec0bf23a2040f1df850175a55f4081480706ff Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Thu, 28 Jul 2022 17:41:04 +0800 Subject: [PATCH 07/13] fix: Fix unit test errors --- .../Masa.Contrib.Configuration.Tests.csproj | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/Masa.Contrib.Configuration.Tests/Masa.Contrib.Configuration.Tests.csproj b/test/Masa.Contrib.Configuration.Tests/Masa.Contrib.Configuration.Tests.csproj index c7631538c..4a044c889 100644 --- a/test/Masa.Contrib.Configuration.Tests/Masa.Contrib.Configuration.Tests.csproj +++ b/test/Masa.Contrib.Configuration.Tests/Masa.Contrib.Configuration.Tests.csproj @@ -42,6 +42,10 @@ Always + + + Always + From 9efe9a740714b5cf01f2fb664f24e1a529d70268 Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Fri, 29 Jul 2022 09:42:09 +0800 Subject: [PATCH 08/13] chore: using global version --- .../Masa.Contrib.BasicAbility.Auth.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Masa.Contrib.BasicAbility.Auth.csproj b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Masa.Contrib.BasicAbility.Auth.csproj index dc927aa13..7fb81b179 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Masa.Contrib.BasicAbility.Auth.csproj +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Masa.Contrib.BasicAbility.Auth.csproj @@ -8,7 +8,7 @@ - + From 5b11bdd3d98143f5d44f9773b3209dfa267252f5 Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Fri, 29 Jul 2022 11:45:06 +0800 Subject: [PATCH 09/13] rename: Rename parameters and classes --- .../AuthClient.cs | 12 +- .../Service/PermissionService.cs | 18 +- .../Service/ProjectService.cs | 8 +- .../Service/SubjectService.cs | 8 +- .../Service/TeamService.cs | 14 +- .../Service/UserService.cs | 50 ++--- .../ServiceCollectionExtensions.cs | 2 +- .../Masa.Contrib.BasicAbility.Mc/McClient.cs | 12 +- .../Service/ChannelService.cs | 10 +- .../Service/MessageTaskService.cs | 12 +- .../Service/MessageTemplateService.cs | 10 +- .../Service/ReceiverGroupService.cs | 10 +- .../Service/WebsiteMessageService.cs | 26 +-- .../ServiceCollectionExtensions.cs | 2 +- .../Masa.Contrib.BasicAbility.Pm/PmClient.cs | 10 +- .../Service/AppService.cs | 16 +- .../Service/ClusterService.cs | 14 +- .../Service/EnvironmentService.cs | 10 +- .../Service/ProjectService.cs | 18 +- .../ServiceCollectionExtensions.cs | 2 +- .../SchedulerClient.cs | 6 +- .../ServiceCollectionExtensions.cs | 2 +- .../Services/SchedulerJobService.cs | 16 +- .../Services/SchedulerTaskService.cs | 10 +- .../Extensions/CallerProviderExtensions.cs | 2 +- .../Extensions/ServiceExtensions.cs | 2 +- .../Service/LogService.cs | 4 +- .../Service/MetricService.cs | 4 +- .../TscClient.cs | 6 +- src/BuildingBlocks/MASA.BuildingBlocks | 2 +- .../ConfigurationApiManage.cs | 10 +- .../Internal/DccFactory.cs | 4 +- .../MasaConfigurationExtensions.cs | 5 +- .../README.md | 2 +- src/Ddd/Masa.Contrib.Ddd.Domain/README.md | 6 +- .../Masa.Contrib.Ddd.Domain/README.zh-CN.md | 6 +- .../README.md | 4 +- .../README.zh-CN.md | 4 +- .../CallerOptionsExtensions.cs | 2 +- .../{DaprCallerProvider.cs => DaprCaller.cs} | 4 +- .../README.md | 20 +- .../README.zh-CN.md | 20 +- .../CallerOptionsExtensions.cs | 2 +- ...tCallerProvider.cs => HttpClientCaller.cs} | 4 +- ...a.Contrib.Service.Caller.HttpClient.csproj | 4 +- .../README.md | 38 ++-- .../README.zh-CN.md | 36 ++-- .../DefaultCallerFactory.cs | 4 +- ...nvertProvider.cs => DefaultTypeConvert.cs} | 2 +- .../Internal/XmlUtils.cs | 26 +++ .../Masa.Contrib.Service.Caller/README.md | 8 +- .../README.zh-CN.md | 8 +- .../ServiceCollectionExtensions.cs | 4 +- .../XmlRequestMessage.cs | 28 +++ .../Masa.Contrib.Service.Caller/_Imports.cs | 2 + .../README.md | 2 +- .../PermissionServiceTest.cs | 46 ++--- .../ProjectServiceTest.cs | 8 +- .../SubjectServiceTest.cs | 8 +- .../TeamServiceTest.cs | 24 +-- .../UserServiceTest.cs | 188 +++++++++--------- .../ChannelServiceTest.cs | 16 +- .../MessageTaskServiceTest.cs | 24 +-- .../MessageTemplateServiceTest.cs | 16 +- .../ReceiverGroupServiceTest.cs | 16 +- .../WebsiteMessageServiceTest.cs | 64 +++--- .../AppServiceTest.cs | 80 ++++---- .../ClusterServiceTest.cs | 64 +++--- .../EnvironmentServiceTest.cs | 32 +-- .../ProjectServiceTest.cs | 96 ++++----- .../SchedulerJobServiceTest.cs | 80 ++++---- .../SchedulerTaskServiceTest.cs | 16 +- .../CallerProviderExtensionsTests.cs | 6 +- .../Service/LogServiceTests.cs | 18 +- .../Service/MetricServiceTests.cs | 6 +- .../DccManageTest.cs | 28 +-- .../DccTest.cs | 4 +- ...stomizeDbContext.cs => CustomDbContext.cs} | 4 +- .../DbContextTest.cs | 10 +- .../Internal/Repository.cs | 4 +- .../TestBase.cs | 6 +- ....cs => CustomDistributedWorkerProvider.cs} | 4 +- .../IdGeneratorTest.cs | 2 +- ...stomizeDbContext.cs => CustomDbContext.cs} | 4 +- .../DomainEventTest.cs | 18 +- .../Domain/Repositories/IOrderRepository.cs | 2 +- .../Repositories/OrderRepository.cs | 4 +- .../RepositoryTest.cs | 20 +- .../DomainEventBusTest.cs | 8 +- ...eDomainEvent.cs => CustomDomainCommand.cs} | 6 +- ...eDomainCommand.cs => CustomDomainEvent.cs} | 6 +- .../CustomDbContext.cs | 4 +- .../FeaturesTest.cs | 4 +- .../DispatcherOptionTest.cs | 2 +- .../IntegrationEventBusTest.cs | 14 +- .../ProcessorTest.cs | 14 +- .../BackgroundServiceTest.cs | 6 +- ...=> CustomIntegrationEventHostedService.cs} | 4 +- ...cs => CustomIntegrationEventLogService.cs} | 2 +- ...stomizeProcessor.cs => CustomProcessor.cs} | 4 +- .../IntegrationEventBusTest.cs | 6 +- .../ProcessorTest.cs | 14 +- ...stomizeDbContext.cs => CustomDbContext.cs} | 4 +- .../Masa.Contrib.Dispatcher.Tests/TestBase.cs | 8 +- .../TestDispatcher.cs | 6 +- .../AutomaticCallerTest.cs | 2 + .../CallerTest.cs | 18 +- .../Callers/DaprCaller.cs | 2 +- .../Callers/GithubCaller.cs | 2 +- .../CallerTest.cs | 20 +- ...rProvider.cs => CustomHttpClientCaller.cs} | 4 +- .../HttpClientCallerTest.cs | 20 +- .../TypeConvertTest.cs | 2 +- .../Utils/XmlUtils.cs | 7 +- .../XmlRequestMessage.cs | 17 -- .../_Imports.cs | 1 - ...rovider.cs => CustomCredentialProvider.cs} | 4 +- ...omizeNullClient.cs => CustomNullClient.cs} | 4 +- .../CustomizeClient.cs | 4 +- .../TestClient.cs | 4 +- .../TestCredentialProvider.cs | 12 +- 121 files changed, 884 insertions(+), 842 deletions(-) rename src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/{DaprCallerProvider.cs => DaprCaller.cs} (96%) rename src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/{HttpClientCallerProvider.cs => HttpClientCaller.cs} (94%) rename src/Service/Caller/Masa.Contrib.Service.Caller/{DefaultTypeConvertProvider.cs => DefaultTypeConvert.cs} (98%) create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/Internal/XmlUtils.cs create mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/XmlRequestMessage.cs rename test/Masa.Contrib.Data.EntityFrameworkCore.Tests/{CustomizeDbContext.cs => CustomDbContext.cs} (74%) rename test/Masa.Contrib.Data.IdGenerator.Snowflake.Tests/{CustomizeDistributedWorkerProvider.cs => CustomDistributedWorkerProvider.cs} (78%) rename test/Masa.Contrib.Ddd.Domain.Integrated.Tests/{CustomizeDbContext.cs => CustomDbContext.cs} (61%) rename test/Masa.Contrib.Ddd.Domain.Tests/Events/{CustomizeDomainEvent.cs => CustomDomainCommand.cs} (54%) rename test/Masa.Contrib.Ddd.Domain.Tests/Events/{CustomizeDomainCommand.cs => CustomDomainEvent.cs} (53%) rename test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/{CustomizeIntegrationEventHostedService.cs => CustomIntegrationEventHostedService.cs} (80%) rename test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/{CustomizeIntegrationEventLogService.cs => CustomIntegrationEventLogService.cs} (93%) rename test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/{CustomizeProcessor.cs => CustomProcessor.cs} (76%) rename test/Masa.Contrib.Dispatcher.Tests/Infrastructure/{CustomizeDbContext.cs => CustomDbContext.cs} (68%) rename test/Masa.Contrib.Service.Caller.Tests/{CustomHttpClientCallerProvider.cs => CustomHttpClientCaller.cs} (66%) delete mode 100644 test/Masa.Contrib.Service.Caller.Tests/XmlRequestMessage.cs rename test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/{CustomizeCredentialProvider.cs => CustomCredentialProvider.cs} (91%) rename test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/{CustomizeNullClient.cs => CustomNullClient.cs} (86%) diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/AuthClient.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/AuthClient.cs index 79af2f22c..8ac52793f 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/AuthClient.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/AuthClient.cs @@ -5,13 +5,13 @@ namespace Masa.Contrib.BasicAbility.Auth; public class AuthClient : IAuthClient { - public AuthClient(ICallerProvider callerProvider, IMultiEnvironmentUserContext userContext) + public AuthClient(ICaller caller, IMultiEnvironmentUserContext userContext) { - UserService = new UserService(callerProvider, userContext); - SubjectService = new SubjectService(callerProvider); - TeamService = new TeamService(callerProvider, userContext); - ProjectService = new ProjectService(callerProvider, userContext); - PermissionService = new PermissionService(callerProvider, userContext); + UserService = new UserService(caller, userContext); + SubjectService = new SubjectService(caller); + TeamService = new TeamService(caller, userContext); + ProjectService = new ProjectService(caller, userContext); + PermissionService = new PermissionService(caller, userContext); } public IUserService UserService { get; } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/PermissionService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/PermissionService.cs index 55936034e..3799b1ea3 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/PermissionService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/PermissionService.cs @@ -5,14 +5,14 @@ namespace Masa.Contrib.BasicAbility.Auth.Service; public class PermissionService : IPermissionService { - readonly ICallerProvider _callerProvider; + readonly ICaller _caller; readonly IUserContext _userContext; const string PART = "api/permission/"; - public PermissionService(ICallerProvider callerProvider, IUserContext userContext) + public PermissionService(ICaller caller, IUserContext userContext) { - _callerProvider = callerProvider; + _caller = caller; _userContext = userContext; } @@ -21,21 +21,21 @@ public async Task AuthorizedAsync(string appId, string code) { var userId = _userContext.GetUserId(); var requestUri = $"{PART}authorized?appId={appId}&code={code}&userId={userId}"; - return await _callerProvider.GetAsync(requestUri); + return await _caller.GetAsync(requestUri); } public async Task> GetMenusAsync(string appId) { var userId = _userContext.GetUserId(); var requestUri = $"{PART}menus?appId={appId}&userId={userId}"; - return await _callerProvider.GetAsync>(requestUri, default) ?? new(); + return await _caller.GetAsync>(requestUri, default) ?? new(); } public async Task> GetElementPermissionsAsync(string appId) { var userId = _userContext.GetUserId(); var requestUri = $"{PART}element-permissions?appId={appId}&userId={userId}"; - return await _callerProvider.GetAsync>(requestUri, default) ?? new(); + return await _caller.GetAsync>(requestUri, default) ?? new(); } public async Task AddFavoriteMenuAsync(Guid menuId) @@ -43,7 +43,7 @@ public async Task AddFavoriteMenuAsync(Guid menuId) try { var userId = _userContext.GetUserId(); - await _callerProvider.PutAsync($"{PART}addFavoriteMenu?permissionId={menuId}&userId={userId}", null); + await _caller.PutAsync($"{PART}addFavoriteMenu?permissionId={menuId}&userId={userId}", null); return true; } catch @@ -57,7 +57,7 @@ public async Task RemoveFavoriteMenuAsync(Guid menuId) try { var userId = _userContext.GetUserId(); - await _callerProvider.PutAsync($"{PART}removeFavoriteMenu?permissionId={menuId}&userId={userId}", null); + await _caller.PutAsync($"{PART}removeFavoriteMenu?permissionId={menuId}&userId={userId}", null); return true; } catch @@ -70,6 +70,6 @@ public async Task> GetFavoriteMenuListAsync() { var userId = _userContext.GetUserId(); var requestUri = $"{PART}menu-favorite-list?userId={userId}"; - return await _callerProvider.GetAsync>(requestUri, default) ?? new(); + return await _caller.GetAsync>(requestUri, default) ?? new(); } } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/ProjectService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/ProjectService.cs index ef4d19778..396dd423e 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/ProjectService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/ProjectService.cs @@ -5,14 +5,14 @@ namespace Masa.Contrib.BasicAbility.Auth.Service; public class ProjectService : IProjectService { - readonly ICallerProvider _callerProvider; + readonly ICaller _caller; readonly IMultiEnvironmentUserContext _multiEnvironmentUserContext; const string PARTY = "api/project/"; - public ProjectService(ICallerProvider callerProvider, IMultiEnvironmentUserContext multiEnvironmentUserContext) + public ProjectService(ICaller caller, IMultiEnvironmentUserContext multiEnvironmentUserContext) { - _callerProvider = callerProvider; + _caller = caller; _multiEnvironmentUserContext = multiEnvironmentUserContext; } @@ -21,6 +21,6 @@ public async Task> GetGlobalNavigations() var userId = _multiEnvironmentUserContext.GetUserId(); var environment = _multiEnvironmentUserContext.Environment ?? ""; var requestUri = $"{PARTY}navigations?userId={userId}&environment={environment}"; - return await _callerProvider.GetAsync>(requestUri) ?? new(); + return await _caller.GetAsync>(requestUri) ?? new(); } } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/SubjectService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/SubjectService.cs index c9599f827..8ed57be5e 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/SubjectService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/SubjectService.cs @@ -5,17 +5,17 @@ namespace Masa.Contrib.BasicAbility.Auth.Service; public class SubjectService : ISubjectService { - readonly ICallerProvider _callerProvider; + readonly ICaller _caller; - public SubjectService(ICallerProvider callerProvider) + public SubjectService(ICaller caller) { - _callerProvider = callerProvider; + _caller = caller; } public async Task> GetListAsync(string filter) { var requestUri = $"api/subject/getList"; - return await _callerProvider.GetAsync>(requestUri, new { filter }) ?? new(); + return await _caller.GetAsync>(requestUri, new { filter }) ?? new(); } } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/TeamService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/TeamService.cs index 49d5c6ecc..2cef018f3 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/TeamService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/TeamService.cs @@ -5,20 +5,20 @@ namespace Masa.Contrib.BasicAbility.Auth.Service; public class TeamService : ITeamService { - readonly ICallerProvider _callerProvider; + readonly ICaller _caller; readonly string _party = "api/team/"; readonly IUserContext _userContext; - public TeamService(ICallerProvider callerProvider, IUserContext userContext) + public TeamService(ICaller caller, IUserContext userContext) { - _callerProvider = callerProvider; + _caller = caller; _userContext = userContext; } public async Task GetDetailAsync(Guid id) { var requestUri = $"{_party}detail"; - return await _callerProvider.GetAsync(requestUri, new { id }); + return await _caller.GetAsync(requestUri, new { id }); } public async Task> GetListAsync(Guid userId = default) @@ -28,20 +28,20 @@ public async Task> GetListAsync(Guid userId = default) { requestUri = $"{requestUri}?userId={userId}"; } - return await _callerProvider.GetAsync>(requestUri) ?? new(); + return await _caller.GetAsync>(requestUri) ?? new(); } public async Task> GetAllAsync() { var requestUri = $"{_party}list"; - return await _callerProvider.GetAsync>(requestUri) ?? new(); + return await _caller.GetAsync>(requestUri) ?? new(); } public async Task> GetUserTeamsAsync() { var userId = _userContext.GetUserId(); var requestUri = $"{_party}list?userId={userId}"; - return await _callerProvider.GetAsync>(requestUri) ?? new(); + return await _caller.GetAsync>(requestUri) ?? new(); } } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/UserService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/UserService.cs index ef9ce0cd4..9ee9970c0 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/UserService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/Service/UserService.cs @@ -5,106 +5,106 @@ namespace Masa.Contrib.BasicAbility.Auth.Service; public class UserService : IUserService { - readonly ICallerProvider _callerProvider; + readonly ICaller _caller; readonly IUserContext _userContext; - public UserService(ICallerProvider callerProvider, IUserContext userContext) + public UserService(ICaller caller, IUserContext userContext) { - _callerProvider = callerProvider; + _caller = caller; _userContext = userContext; } public async Task AddAsync(AddUserModel user) { var requestUri = $"api/user/addExternal"; - return await _callerProvider.PostAsync(requestUri, user); + return await _caller.PostAsync(requestUri, user); } public async Task UpsertAsync(UpsertUserModel user) { var requestUri = $"api/user/upsertExternal"; - return await _callerProvider.PostAsync(requestUri, user); + return await _caller.PostAsync(requestUri, user); } public async Task> GetListByDepartmentAsync(Guid departmentId) { var requestUri = $"api/staff/getListByDepartment"; - return await _callerProvider.GetAsync>(requestUri, new { id = departmentId }) ?? new(); + return await _caller.GetAsync>(requestUri, new { id = departmentId }) ?? new(); } public async Task> GetListByRoleAsync(Guid roleId) { var requestUri = $"api/staff/getListByRole"; - return await _callerProvider.GetAsync>(requestUri, new { id = roleId }) ?? new(); + return await _caller.GetAsync>(requestUri, new { id = roleId }) ?? new(); } public async Task> GetListByTeamAsync(Guid teamId) { var requestUri = $"api/staff/getListByTeam"; - return await _callerProvider.GetAsync>(requestUri, new { id = teamId }) ?? new(); + return await _caller.GetAsync>(requestUri, new { id = teamId }) ?? new(); } public async Task GetTotalByDepartmentAsync(Guid departmentId) { var requestUri = $"api/staff/getTotalByDepartment"; - return await _callerProvider.GetAsync(requestUri, new { id = departmentId }); + return await _caller.GetAsync(requestUri, new { id = departmentId }); } public async Task GetTotalByRoleAsync(Guid roleId) { var requestUri = $"api/staff/getTotalByRole"; - return await _callerProvider.GetAsync(requestUri, new { id = roleId }); + return await _caller.GetAsync(requestUri, new { id = roleId }); } public async Task GetTotalByTeamAsync(Guid teamId) { var requestUri = $"api/staff/getTotalByTeam"; - return await _callerProvider.GetAsync(requestUri, new { id = teamId }); + return await _caller.GetAsync(requestUri, new { id = teamId }); } public async Task ValidateCredentialsByAccountAsync(string account, string password) { var requestUri = $"api/user/validateByAccount"; - return await _callerProvider.PostAsync(requestUri, new { account, password }); + return await _caller.PostAsync(requestUri, new { account, password }); } public async Task FindByAccountAsync(string account) { var requestUri = $"api/user/findByAccount"; - return await _callerProvider.GetAsync(requestUri, new { account }) ?? new(); + return await _caller.GetAsync(requestUri, new { account }) ?? new(); } public async Task FindByPhoneNumberAsync(string phoneNumber) { var requestUri = $"api/user/findByPhoneNumber"; - return await _callerProvider.GetAsync(requestUri, new { phoneNumber }); + return await _caller.GetAsync(requestUri, new { phoneNumber }); } public async Task FindByEmailAsync(string email) { var requestUri = $"api/user/findByEmail"; - return await _callerProvider.GetAsync(requestUri, new { email }); + return await _caller.GetAsync(requestUri, new { email }); } public async Task GetCurrentUserAsync() { var id = _userContext.GetUserId(); var requestUri = $"api/user/findById"; - return await _callerProvider.GetAsync(requestUri, new { id }) ?? new(); + return await _caller.GetAsync(requestUri, new { id }) ?? new(); } public async Task VisitedAsync(string url) { var userId = _userContext.GetUserId(); var requestUri = $"api/user/visit"; - await _callerProvider.PostAsync(requestUri, new { UserId = userId, Url = url }, true); + await _caller.PostAsync(requestUri, new { UserId = userId, Url = url }, true); } public async Task> GetVisitedListAsync() { var userId = _userContext.GetUserId(); var requestUri = $"api/user/visitedList"; - return (await _callerProvider.GetAsync>(requestUri, new { userId = userId })) ?? new(); + return (await _caller.GetAsync>(requestUri, new { userId = userId })) ?? new(); } public async Task UpdatePasswordAsync(UpdateUserPasswordModel user) @@ -114,7 +114,7 @@ public async Task UpdatePasswordAsync(UpdateUserPasswordModel user) user.Id = _userContext.GetUserId(); } var requestUri = $"api/user/updatePassword"; - await _callerProvider.PutAsync(requestUri, user); + await _caller.PutAsync(requestUri, user); } public async Task UpdateBasicInfoAsync(UpdateUserBasicInfoModel user) @@ -124,20 +124,20 @@ public async Task UpdateBasicInfoAsync(UpdateUserBasicInfoModel user) user.Id = _userContext.GetUserId(); } var requestUri = $"api/user/updateBasicInfo"; - await _callerProvider.PutAsync(requestUri, user); + await _caller.PutAsync(requestUri, user); } public async Task> GetUserPortraitsAsync(params Guid[] userIds) { var requestUri = $"api/user/portraits"; - return await _callerProvider.PostAsync>(requestUri, userIds) ?? new(); + return await _caller.PostAsync>(requestUri, userIds) ?? new(); } public async Task SaveUserSystemDataAsync(string systemId, T data) { var userId = _userContext.GetUserId(); var requestUri = $"api/user/UserSystemData"; - await _callerProvider.PostAsync(requestUri, + await _caller.PostAsync(requestUri, new { UserId = userId, SystemId = systemId, Data = JsonSerializer.Serialize(data) }, true); } @@ -146,20 +146,20 @@ await _callerProvider.PostAsync(requestUri, { var userId = _userContext.GetUserId(); var requestUri = $"api/user/GetUserSystemData"; - var data = await _callerProvider.GetAsync(requestUri, new { userId = userId, systemId = systemId }); + var data = await _caller.GetAsync(requestUri, new { userId = userId, systemId = systemId }); return JsonSerializer.Deserialize(data); } public async Task DisableUserAsync(DisableUserModel user) { var requestUri = $"api/user/disable"; - return await _callerProvider.PutAsync(requestUri, user); + return await _caller.PutAsync(requestUri, user); } public async Task> GetListByAccountAsync(IEnumerable accounts) { var requestUri = $"api/user/GetListByAccount"; - return await _callerProvider.GetAsync>(requestUri, new { accounts }) ?? new(); + return await _caller.GetAsync>(requestUri, new { accounts }) ?? new(); } } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/ServiceCollectionExtensions.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/ServiceCollectionExtensions.cs index 538e8bb2a..806af9775 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/ServiceCollectionExtensions.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Auth/ServiceCollectionExtensions.cs @@ -33,7 +33,7 @@ public static IServiceCollection AddAuthClient(this IServiceCollection services, services.AddScoped(serviceProvider => { var userContext = serviceProvider.GetRequiredService(); - var callProvider = serviceProvider.GetRequiredService().CreateClient(DEFAULT_CLIENT_NAME); + var callProvider = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); var authClient = new AuthClient(callProvider, userContext); return authClient; }); diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/McClient.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/McClient.cs index 60f2c4a9e..2d36b136b 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/McClient.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/McClient.cs @@ -5,13 +5,13 @@ namespace Masa.Contrib.BasicAbility.Mc; public class McClient: IMcClient { - public McClient(ICallerProvider callerProvider) + public McClient(ICaller caller) { - ChannelService = new ChannelService(callerProvider); - MessageTaskService = new MessageTaskService(callerProvider); - MessageTemplateService = new MessageTemplateService(callerProvider); - ReceiverGroupService = new ReceiverGroupService(callerProvider); - WebsiteMessageService = new WebsiteMessageService(callerProvider); + ChannelService = new ChannelService(caller); + MessageTaskService = new MessageTaskService(caller); + MessageTemplateService = new MessageTemplateService(caller); + ReceiverGroupService = new ReceiverGroupService(caller); + WebsiteMessageService = new WebsiteMessageService(caller); } public IChannelService ChannelService { get; } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/ChannelService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/ChannelService.cs index 4698a5e7e..8ef58d3d0 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/ChannelService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/ChannelService.cs @@ -5,23 +5,23 @@ namespace Masa.Contrib.BasicAbility.Mc.Service; public class ChannelService : IChannelService { - readonly ICallerProvider _callerProvider; + readonly ICaller _caller; readonly string _party = "api/channel"; - public ChannelService(ICallerProvider callerProvider) + public ChannelService(ICaller caller) { - _callerProvider = callerProvider; + _caller = caller; } public async Task GetAsync(Guid id) { var requestUri = $"{_party}/{id}"; - return await _callerProvider.GetAsync(requestUri); + return await _caller.GetAsync(requestUri); } public async Task> GetListAsync(GetChannelModel options) { var requestUri = $"{_party}"; - return await _callerProvider.GetAsync>(requestUri, options) ?? new(); + return await _caller.GetAsync>(requestUri, options) ?? new(); } } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/MessageTaskService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/MessageTaskService.cs index 50f3a8c7d..0ec4753d4 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/MessageTaskService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/MessageTaskService.cs @@ -5,29 +5,29 @@ namespace Masa.Contrib.BasicAbility.Mc.Service; public class MessageTaskService : IMessageTaskService { - readonly ICallerProvider _callerProvider; + readonly ICaller _caller; readonly string _party = "api/message-task"; - public MessageTaskService(ICallerProvider callerProvider) + public MessageTaskService(ICaller caller) { - _callerProvider = callerProvider; + _caller = caller; } public async Task GetAsync(Guid id) { var requestUri = $"{_party}/{id}"; - return await _callerProvider.GetAsync(requestUri); + return await _caller.GetAsync(requestUri); } public async Task SendOrdinaryMessageAsync(SendOrdinaryMessageModel options) { var requestUri = $"{_party}/SendOrdinaryMessage"; - await _callerProvider.PostAsync(requestUri, options); + await _caller.PostAsync(requestUri, options); } public async Task SendTemplateMessageAsync(SendTemplateMessageModel options) { var requestUri = $"{_party}/SendTemplateMessage"; - await _callerProvider.PostAsync(requestUri, options); + await _caller.PostAsync(requestUri, options); } } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/MessageTemplateService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/MessageTemplateService.cs index 5a110ce81..7d86b70d2 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/MessageTemplateService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/MessageTemplateService.cs @@ -5,23 +5,23 @@ namespace Masa.Contrib.BasicAbility.Mc.Service; public class MessageTemplateService : IMessageTemplateService { - readonly ICallerProvider _callerProvider; + readonly ICaller _caller; readonly string _party = "api/message-template"; - public MessageTemplateService(ICallerProvider callerProvider) + public MessageTemplateService(ICaller caller) { - _callerProvider = callerProvider; + _caller = caller; } public async Task GetAsync(Guid id) { var requestUri = $"{_party}/{id}"; - return await _callerProvider.GetAsync(requestUri); + return await _caller.GetAsync(requestUri); } public async Task> GetListAsync(GetMessageTemplateModel options) { var requestUri = $"{_party}"; - return await _callerProvider.GetAsync>(requestUri, options) ?? new(); + return await _caller.GetAsync>(requestUri, options) ?? new(); } } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/ReceiverGroupService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/ReceiverGroupService.cs index a6b6606ab..ec6a8c23e 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/ReceiverGroupService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/ReceiverGroupService.cs @@ -5,23 +5,23 @@ namespace Masa.Contrib.BasicAbility.Mc.Service; public class ReceiverGroupService : IReceiverGroupService { - readonly ICallerProvider _callerProvider; + readonly ICaller _caller; readonly string _party = "api/receiver-group"; - public ReceiverGroupService(ICallerProvider callerProvider) + public ReceiverGroupService(ICaller caller) { - _callerProvider = callerProvider; + _caller = caller; } public async Task GetAsync(Guid id) { var requestUri = $"{_party}/{id}"; - return await _callerProvider.GetAsync(requestUri); + return await _caller.GetAsync(requestUri); } public async Task> GetListAsync(GetReceiverGroupModel options) { var requestUri = $"{_party}"; - return await _callerProvider.GetAsync>(requestUri, options) ?? new(); + return await _caller.GetAsync>(requestUri, options) ?? new(); } } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/WebsiteMessageService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/WebsiteMessageService.cs index 58f1ac4ea..704cff7e0 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/WebsiteMessageService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/Service/WebsiteMessageService.cs @@ -2,71 +2,71 @@ namespace Masa.Contrib.BasicAbility.Mc.Service; public class WebsiteMessageService : IWebsiteMessageService { - readonly ICallerProvider _callerProvider; + readonly ICaller _caller; readonly string _party = "api/website-message"; - public WebsiteMessageService(ICallerProvider callerProvider) + public WebsiteMessageService(ICaller caller) { - _callerProvider = callerProvider; + _caller = caller; } public async Task CheckAsync() { var requestUri = $"{_party}/Check"; - await _callerProvider.PostAsync(requestUri, null); + await _caller.PostAsync(requestUri, null); } public async Task DeleteAsync(Guid id) { var requestUri = $"{_party}/{id}"; - await _callerProvider.DeleteAsync(requestUri, null); + await _caller.DeleteAsync(requestUri, null); } public async Task GetAsync(Guid id) { var requestUri = $"{_party}/{id}"; - return await _callerProvider.GetAsync(requestUri); + return await _caller.GetAsync(requestUri); } public async Task> GetChannelListAsync() { var requestUri = $"{_party}/GetChannelList"; - return await _callerProvider.GetAsync>(requestUri)??new(); + return await _caller.GetAsync>(requestUri)??new(); } public async Task> GetListAsync(GetWebsiteMessageModel options) { var requestUri = $"{_party}"; - return await _callerProvider.GetAsync>(requestUri, options) ?? new(); + return await _caller.GetAsync>(requestUri, options) ?? new(); } public async Task> GetNoticeListAsync(GetNoticeListModel options) { var requestUri = $"{_party}/GetNoticeList"; - return await _callerProvider.GetAsync>(requestUri, options) ?? new(); + return await _caller.GetAsync>(requestUri, options) ?? new(); } public async Task ReadAsync(ReadWebsiteMessageModel options) { var requestUri = $"{_party}/Read"; - await _callerProvider.PostAsync(requestUri, options); + await _caller.PostAsync(requestUri, options); } public async Task SetAllReadAsync(ReadAllWebsiteMessageModel options) { var requestUri = $"{_party}/SetAllRead"; - await _callerProvider.PostAsync(requestUri, options); + await _caller.PostAsync(requestUri, options); } public async Task SendCheckNotificationAsync() { var requestUri = $"{_party}/SendCheckNotification"; - await _callerProvider.PostAsync(requestUri, null); + await _caller.PostAsync(requestUri, null); } public async Task SendGetNotificationAsync(List userIds) { var requestUri = $"{_party}/SendGetNotification"; - await _callerProvider.PostAsync(requestUri, userIds); + await _caller.PostAsync(requestUri, userIds); } } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/ServiceCollectionExtensions.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/ServiceCollectionExtensions.cs index 682224c0f..6d039e5eb 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/ServiceCollectionExtensions.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Mc/ServiceCollectionExtensions.cs @@ -35,7 +35,7 @@ public static IServiceCollection AddMcClient(this IServiceCollection services, A services.AddScoped(serviceProvider => { - var callProvider = serviceProvider.GetRequiredService().CreateClient(DEFAULT_CLIENT_NAME); + var callProvider = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); var mcCaching = new McClient(callProvider); return mcCaching; }); diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/PmClient.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/PmClient.cs index 64815356c..845a3a0e2 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/PmClient.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/PmClient.cs @@ -5,12 +5,12 @@ namespace Masa.Contrib.BasicAbility.Pm; public class PmClient : IPmClient { - public PmClient(ICallerProvider callerProvider) + public PmClient(ICaller caller) { - EnvironmentService = new EnvironmentService(callerProvider); - ClusterService = new ClusterService(callerProvider); - ProjectService = new ProjectService(callerProvider); - AppService = new AppService(callerProvider); + EnvironmentService = new EnvironmentService(caller); + ClusterService = new ClusterService(caller); + ProjectService = new ProjectService(caller); + AppService = new AppService(caller); } public IProjectService ProjectService { get; init; } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/AppService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/AppService.cs index 5bb6c2234..40a3c6e24 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/AppService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/AppService.cs @@ -5,17 +5,17 @@ namespace Masa.Contrib.BasicAbility.Pm.Service; public class AppService : IAppService { - private readonly ICallerProvider _callerProvider; + private readonly ICaller _caller; - public AppService(ICallerProvider callerProvider) + public AppService(ICaller caller) { - _callerProvider = callerProvider; + _caller = caller; } public async Task GetAsync(int id) { var requestUri = $"api/v1/app/{id}"; - var result = await _callerProvider.GetAsync(requestUri); + var result = await _caller.GetAsync(requestUri); return result ?? new(); } @@ -23,7 +23,7 @@ public async Task GetAsync(int id) public async Task GetByIdentityAsync(string identity) { var requestUri = $"open-api/app/{identity}"; - var result = await _callerProvider.GetAsync(requestUri); + var result = await _caller.GetAsync(requestUri); return result ?? new(); } @@ -31,7 +31,7 @@ public async Task GetByIdentityAsync(string identity) public async Task> GetListAsync() { var requestUri = $"api/v1/app"; - var result = await _callerProvider.GetAsync>(requestUri); + var result = await _caller.GetAsync>(requestUri); return result ?? new(); } @@ -39,7 +39,7 @@ public async Task> GetListAsync() public async Task> GetListByProjectIdsAsync(List projectIds) { var requestUri = $"api/v1/projects/app"; - var result = await _callerProvider.PostAsync, List>(requestUri, projectIds); + var result = await _caller.PostAsync, List>(requestUri, projectIds); return result ?? new(); } @@ -47,7 +47,7 @@ public async Task> GetListByProjectIdsAsync(List proje public async Task GetWithEnvironmentClusterAsync(int id) { var requestUri = $"api/v1/appWhitEnvCluster/{id}"; - var result = await _callerProvider.GetAsync(requestUri); + var result = await _caller.GetAsync(requestUri); return result ?? new(); } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/ClusterService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/ClusterService.cs index 4aaa60333..9d03a3fd6 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/ClusterService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/ClusterService.cs @@ -5,17 +5,17 @@ namespace Masa.Contrib.BasicAbility.Pm.Service; public class ClusterService : IClusterService { - private readonly ICallerProvider _callerProvider; + private readonly ICaller _caller; - public ClusterService(ICallerProvider callerProvider) + public ClusterService(ICaller caller) { - _callerProvider = callerProvider; + _caller = caller; } public async Task GetAsync(int id) { var requestUri = $"api/v1/cluster/{id}"; - var result = await _callerProvider.GetAsync(requestUri); + var result = await _caller.GetAsync(requestUri); return result ?? new(); } @@ -23,7 +23,7 @@ public async Task GetAsync(int id) public async Task> GetEnvironmentClustersAsync() { var requestUri = $"api/v1/envClusters"; - var result = await _callerProvider.GetAsync>(requestUri); + var result = await _caller.GetAsync>(requestUri); return result ?? new(); } @@ -31,7 +31,7 @@ public async Task> GetEnvironmentClustersAsync() public async Task> GetListAsync() { var requestUri = $"api/v1/cluster"; - var result = await _callerProvider.GetAsync>(requestUri); + var result = await _caller.GetAsync>(requestUri); return result ?? new(); } @@ -39,7 +39,7 @@ public async Task> GetListAsync() public async Task> GetListByEnvIdAsync(int envId) { var requestUri = $"api/v1/{envId}/cluster"; - var result = await _callerProvider.GetAsync>(requestUri); + var result = await _caller.GetAsync>(requestUri); return result ?? new(); } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/EnvironmentService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/EnvironmentService.cs index 8c710a979..3776c92a0 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/EnvironmentService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/EnvironmentService.cs @@ -5,17 +5,17 @@ namespace Masa.Contrib.BasicAbility.Pm.Service; public class EnvironmentService : IEnvironmentService { - private readonly ICallerProvider _callerProvider; + private readonly ICaller _caller; - public EnvironmentService(ICallerProvider callerProvider) + public EnvironmentService(ICaller caller) { - _callerProvider = callerProvider; + _caller = caller; } public async Task GetAsync(int id) { var requestUri = $"api/v1/env/{id}"; - var result = await _callerProvider.GetAsync(requestUri); + var result = await _caller.GetAsync(requestUri); return result ?? new(); } @@ -23,7 +23,7 @@ public async Task GetAsync(int id) public async Task> GetListAsync() { var requestUri = $"api/v1/env"; - var result = await _callerProvider.GetAsync>(requestUri); + var result = await _caller.GetAsync>(requestUri); return result ?? new(); } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/ProjectService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/ProjectService.cs index 7c05efc0a..1f603f936 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/ProjectService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/Service/ProjectService.cs @@ -5,17 +5,17 @@ namespace Masa.Contrib.BasicAbility.Pm.Service; public class ProjectService : IProjectService { - private readonly ICallerProvider _callerProvider; + private readonly ICaller _caller; - public ProjectService(ICallerProvider callerProvider) + public ProjectService(ICaller caller) { - _callerProvider = callerProvider; + _caller = caller; } public async Task> GetProjectAppsAsync(string envName) { var requestUri = $"api/v1/projectwithapps/{envName}"; - var result = await _callerProvider.GetAsync>(requestUri); + var result = await _caller.GetAsync>(requestUri); return result ?? new(); } @@ -23,7 +23,7 @@ public async Task> GetProjectAppsAsync(string envName) public async Task GetAsync(int id) { var requestUri = $"api/v1/project/{id}"; - var result = await _callerProvider.GetAsync(requestUri); + var result = await _caller.GetAsync(requestUri); return result ?? new(); } @@ -31,7 +31,7 @@ public async Task GetAsync(int id) public async Task GetByIdentityAsync(string identity) { var requestUri = $"open-api/project/{identity}"; - var result = await _callerProvider.GetAsync(requestUri); + var result = await _caller.GetAsync(requestUri); return result ?? new(); } @@ -39,7 +39,7 @@ public async Task GetByIdentityAsync(string identity) public async Task> GetListByEnvironmentClusterIdAsync(int envClusterId) { var requestUri = $"api/v1/{envClusterId}/project"; - var result = await _callerProvider.GetAsync>(requestUri); + var result = await _caller.GetAsync>(requestUri); return result ?? new(); } @@ -47,7 +47,7 @@ public async Task> GetListByEnvironmentClusterIdAsync(int env public async Task> GetListByTeamIdsAsync(List teamIds) { var requestUri = $"api/v1/project/teamProjects"; - var result = await _callerProvider.PostAsync>(requestUri, teamIds); + var result = await _caller.PostAsync>(requestUri, teamIds); return result ?? new(); } @@ -55,7 +55,7 @@ public async Task> GetListByTeamIdsAsync(List teamIds) public async Task> GetProjectTypesAsync() { var requestUri = $"api/v1/project/projectType"; - var result = await _callerProvider.GetAsync>(requestUri); + var result = await _caller.GetAsync>(requestUri); return result ?? new(); } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/ServiceCollectionExtensions.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/ServiceCollectionExtensions.cs index ea6c64c99..a3b037996 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/ServiceCollectionExtensions.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Pm/ServiceCollectionExtensions.cs @@ -33,7 +33,7 @@ public static IServiceCollection AddPmClient(this IServiceCollection services, A services.AddSingleton(serviceProvider => { - var callProvider = serviceProvider.GetRequiredService().CreateClient(DEFAULT_CLIENT_NAME); + var callProvider = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); var pmCaching = new PmClient(callProvider); return pmCaching; }); diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/SchedulerClient.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/SchedulerClient.cs index 658cc2755..f67b49b42 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/SchedulerClient.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/SchedulerClient.cs @@ -9,9 +9,9 @@ public class SchedulerClient : ISchedulerClient public ISchedulerTaskService SchedulerTaskService { get; } - public SchedulerClient(ICallerProvider callerProvider, ILoggerFactory? loggerFactory = null) + public SchedulerClient(ICaller caller, ILoggerFactory? loggerFactory = null) { - SchedulerJobService = new SchedulerJobService(callerProvider, loggerFactory); - SchedulerTaskService = new SchedulerTaskService(callerProvider, loggerFactory); + SchedulerJobService = new SchedulerJobService(caller, loggerFactory); + SchedulerTaskService = new SchedulerTaskService(caller, loggerFactory); } } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/ServiceCollectionExtensions.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/ServiceCollectionExtensions.cs index f37be5001..4f27418d7 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/ServiceCollectionExtensions.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/ServiceCollectionExtensions.cs @@ -37,7 +37,7 @@ public static IServiceCollection AddSchedulerClient(this IServiceCollection serv services.AddScoped(serviceProvider => { - var callProvider = serviceProvider.GetRequiredService().CreateClient(DEFAULT_CLIENT_NAME); + var callProvider = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); var loggerFactory = serviceProvider.GetService(); var schedulerClient = new SchedulerClient(callProvider, loggerFactory); return schedulerClient; diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/Services/SchedulerJobService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/Services/SchedulerJobService.cs index 545876bb0..cd777eb44 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/Services/SchedulerJobService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/Services/SchedulerJobService.cs @@ -7,12 +7,12 @@ public class SchedulerJobService : ISchedulerJobService { const string API = "/api/scheduler-job"; - readonly ICallerProvider _callerProvider; + readonly ICaller _caller; readonly ILogger? _logger; - public SchedulerJobService(ICallerProvider callerProvider, ILoggerFactory? loggerFactory = null) + public SchedulerJobService(ICaller caller, ILoggerFactory? loggerFactory = null) { - _callerProvider = callerProvider; + _caller = caller; _logger = loggerFactory?.CreateLogger(); } @@ -39,7 +39,7 @@ public async Task AddAsync(AddSchedulerJobRequest request) try { var requestUri = $"{API}/addSchedulerJobBySdk"; - return await _callerProvider.PostAsync(requestUri, request); + return await _caller.PostAsync(requestUri, request); } catch (Exception ex) { @@ -60,7 +60,7 @@ public async Task DisableAsync(BaseSchedulerJobRequest request) Enabled = false }; var requestUri = $"{API}/changeEnableStatus"; - await _callerProvider.PutAsync(requestUri, requestData); + await _caller.PutAsync(requestUri, requestData); return true; } catch (Exception ex) @@ -81,7 +81,7 @@ public async Task EnableAsync(BaseSchedulerJobRequest request) Enabled = true }; var requestUri = $"{API}/changeEnableStatus"; - await _callerProvider.PutAsync(requestUri, requestData); + await _caller.PutAsync(requestUri, requestData); return true; } catch (Exception ex) @@ -96,7 +96,7 @@ public async Task RemoveAsync(BaseSchedulerJobRequest request) try { var requestUri = $"{API}"; - await _callerProvider.DeleteAsync(requestUri, request); + await _caller.DeleteAsync(requestUri, request); return true; } catch (Exception ex) @@ -111,7 +111,7 @@ public async Task StartAsync(BaseSchedulerJobRequest request) try { var requestUri = $"{API}/startJob"; - await _callerProvider.PutAsync(requestUri, request); + await _caller.PutAsync(requestUri, request); return true; } catch (Exception ex) diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/Services/SchedulerTaskService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/Services/SchedulerTaskService.cs index 29806b4d5..646bef817 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/Services/SchedulerTaskService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/Services/SchedulerTaskService.cs @@ -7,12 +7,12 @@ public class SchedulerTaskService : ISchedulerTaskService { const string API = "/api/scheduler-task"; - readonly ICallerProvider _callerProvider; + readonly ICaller _caller; readonly ILogger? _logger; - public SchedulerTaskService(ICallerProvider callerProvider, ILoggerFactory? loggerFactory) + public SchedulerTaskService(ICaller caller, ILoggerFactory? loggerFactory) { - _callerProvider = callerProvider; + _caller = caller; _logger = loggerFactory?.CreateLogger(); } @@ -21,7 +21,7 @@ public async Task StopAsync(BaseSchedulerTaskRequest request) try { var requestUri = $"{API}/stop"; - await _callerProvider.PutAsync(requestUri, request); + await _caller.PutAsync(requestUri, request); return true; } catch (Exception ex) @@ -43,7 +43,7 @@ public async Task StartAsync(BaseSchedulerTaskRequest request) }; var requestUri = $"{API}/start"; - await _callerProvider.PutAsync(requestUri, requestData); + await _caller.PutAsync(requestUri, requestData); return true; } catch (Exception ex) diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Extensions/CallerProviderExtensions.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Extensions/CallerProviderExtensions.cs index 1078d7435..50c9d1063 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Extensions/CallerProviderExtensions.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Extensions/CallerProviderExtensions.cs @@ -6,7 +6,7 @@ namespace Masa.Contrib.Service.Caller; internal static class CallerProviderExtensions { - public static async Task GetByBodyAsync(this ICallerProvider caller, string url, object? body) where TResult : class + public static async Task GetByBodyAsync(this ICaller caller, string url, object? body) where TResult : class { var request = new HttpRequestMessage(HttpMethod.Get, url); if (body is not null) diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Extensions/ServiceExtensions.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Extensions/ServiceExtensions.cs index 4195c5521..163b295c0 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Extensions/ServiceExtensions.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Extensions/ServiceExtensions.cs @@ -26,7 +26,7 @@ public static IServiceCollection AddTscClient(this IServiceCollection services, services.AddSingleton(serviceProvider => { - var caller = serviceProvider.GetRequiredService().CreateClient(DEFAULT_CLIENT_NAME); + var caller = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); var pmCaching = new TscClient(caller); return pmCaching; }); diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Service/LogService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Service/LogService.cs index 6377d136d..897e9d9dd 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Service/LogService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Service/LogService.cs @@ -5,12 +5,12 @@ namespace Masa.Contrib.BasicAbility.Tsc.Service; public class LogService : ILogService { - private readonly ICallerProvider _caller; + private readonly ICaller _caller; internal const string AGGREGATION_URI = "/api/log/aggregation"; internal const string LATEST_URI = "/api/log/latest"; internal const string FIELD_URI = "/api/log/field"; - public LogService(ICallerProvider caller) + public LogService(ICaller caller) { _caller = caller; } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Service/MetricService.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Service/MetricService.cs index 5bbc83185..e0313a0c1 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Service/MetricService.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/Service/MetricService.cs @@ -5,12 +5,12 @@ namespace Masa.Contrib.BasicAbility.Tsc.Service; internal class MetricService : IMetricService { - private readonly ICallerProvider _caller; + private readonly ICaller _caller; internal const string RANGEVALUES_URL = "/api/metric/range-values"; internal const string NAMES_URI = "/api/metric/names"; internal const string LABELVALUES_URI = "/api/metric/label-values"; - public MetricService(ICallerProvider caller) + public MetricService(ICaller caller) { _caller = caller; } diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/TscClient.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/TscClient.cs index c0acf6ee4..67e2a052f 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/TscClient.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Tsc/TscClient.cs @@ -6,10 +6,10 @@ namespace Masa.Contrib.BasicAbility.Tsc; internal class TscClient : ITscClient { - public TscClient(ICallerProvider callerProvider) + public TscClient(ICaller caller) { - LogService = new LogService(callerProvider); - MetricService = new MetricService(callerProvider); + LogService = new LogService(caller); + MetricService = new MetricService(caller); } public ILogService LogService { get; } diff --git a/src/BuildingBlocks/MASA.BuildingBlocks b/src/BuildingBlocks/MASA.BuildingBlocks index 869794569..1b419d05a 160000 --- a/src/BuildingBlocks/MASA.BuildingBlocks +++ b/src/BuildingBlocks/MASA.BuildingBlocks @@ -1 +1 @@ -Subproject commit 869794569eb140e5bbc208ee02b14e22c90cf8f6 +Subproject commit 1b419d05aa21b265a06a975e72f9a44dfdf49036 diff --git a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/ConfigurationApiManage.cs b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/ConfigurationApiManage.cs index dfad56c97..e4a6951e9 100644 --- a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/ConfigurationApiManage.cs +++ b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/ConfigurationApiManage.cs @@ -5,22 +5,22 @@ namespace Masa.Contrib.Configuration.ConfigurationApi.Dcc; public class ConfigurationApiManage : ConfigurationApiBase, IConfigurationApiManage { - private readonly ICallerProvider _callerProvider; + private readonly ICaller _caller; public ConfigurationApiManage( - ICallerProvider callerProvider, + ICaller caller, DccSectionOptions defaultSectionOption, List? expandSectionOptions) : base(defaultSectionOption, expandSectionOptions) { - _callerProvider = callerProvider; + _caller = caller; } /// public async Task InitializeAsync(string environment, string cluster, string appId, Dictionary configObjects) { var requestUri = $"open-api/releasing/init/{GetEnvironment(environment)}/{GetCluster(cluster)}/{GetAppId(appId)}"; - var result = await _callerProvider.PostAsync(requestUri, configObjects, default); + var result = await _caller.PostAsync(requestUri, configObjects, default); // 299 is the status code when throwing a UserFriendlyException in masa.framework if ((int)result.StatusCode == 299 || !result.IsSuccessStatusCode) @@ -33,7 +33,7 @@ public async Task InitializeAsync(string environment, string cluster, string app public async Task UpdateAsync(string environment, string cluster, string appId, string configObject, object value) { var requestUri = $"open-api/releasing/{GetEnvironment(environment)}/{GetCluster(cluster)}/{GetAppId(appId)}/{GetConfigObject(configObject)}"; - var result = await _callerProvider.PutAsync(requestUri, value, default); + var result = await _caller.PutAsync(requestUri, value, default); // 299 is the status code when throwing a UserFriendlyException in masa.framework if ((int)result.StatusCode == 299 || !result.IsSuccessStatusCode) diff --git a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Internal/DccFactory.cs b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Internal/DccFactory.cs index ee87fa6b0..5aa9592f4 100644 --- a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Internal/DccFactory.cs +++ b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Internal/DccFactory.cs @@ -16,8 +16,8 @@ public static IConfigurationApiClient CreateClient( } public static IConfigurationApiManage CreateManage( - ICallerProvider callerProvider, + ICaller caller, DccSectionOptions defaultSectionOption, List? expandSectionOptions) - => new ConfigurationApiManage(callerProvider, defaultSectionOption, expandSectionOptions); + => new ConfigurationApiManage(caller, defaultSectionOption, expandSectionOptions); } diff --git a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/MasaConfigurationExtensions.cs b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/MasaConfigurationExtensions.cs index 87d8d1122..80b79d983 100644 --- a/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/MasaConfigurationExtensions.cs +++ b/src/Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/MasaConfigurationExtensions.cs @@ -88,7 +88,8 @@ public static IMasaConfigurationBuilder UseDcc( else { action.Invoke(options); - callerName = options.Callers.Select(opt => opt.Name).FirstOrDefault(); + callerName = options.Callers.Select(opt => opt.Name).FirstOrDefault() + ?? throw new Exception("Missing Caller implementation, eg: options.UseHttpClient()"); } }); @@ -138,7 +139,7 @@ public static IServiceCollection TryAddConfigurationApiManage(IServiceCollection services.TryAddSingleton(serviceProvider => { var callerFactory = serviceProvider.GetRequiredService(); - return DccFactory.CreateManage(callerFactory.CreateClient(callerName), defaultSectionOption, expansionSectionOptions); + return DccFactory.CreateManage(callerFactory.Create(callerName), defaultSectionOption, expansionSectionOptions); }); return services; } diff --git a/src/Ddd/Masa.Contrib.Ddd.Domain.Repository.EF/README.md b/src/Ddd/Masa.Contrib.Ddd.Domain.Repository.EF/README.md index 9755c6b38..08c0f8c37 100644 --- a/src/Ddd/Masa.Contrib.Ddd.Domain.Repository.EF/README.md +++ b/src/Ddd/Masa.Contrib.Ddd.Domain.Repository.EF/README.md @@ -43,7 +43,7 @@ public class DemoService : ServiceBase } ``` -If the method defined by IRepository is not enough to support the business, you can customize the Repository +If the method defined by IRepository is not enough to support the business, you can custom the Repository ```C# public interface IProductRepository : IRepository diff --git a/src/Ddd/Masa.Contrib.Ddd.Domain/README.md b/src/Ddd/Masa.Contrib.Ddd.Domain/README.md index f08b81bc0..673abbee7 100644 --- a/src/Ddd/Masa.Contrib.Ddd.Domain/README.md +++ b/src/Ddd/Masa.Contrib.Ddd.Domain/README.md @@ -25,13 +25,13 @@ builder.Services options.UseIntegrationEventBus(opt => { opt.UseDapr(); - opt.UseEventLog();//Use cross-process events + opt.UseEventLog();//Use cross-process events }); options // .UseEventBus(eventBuilder => eventBuilder.UseMiddleware(typeof(ValidatorMiddleware<>))) // Use in-process events and use middleware .UseEventBus() // Use in-process events - .UseUoW(dbOptions => dbOptions.UseSqlServer("server=localhost;uid=sa;pwd=P@ssw0rd;database=idientity")) - .UseRepository();//Use the EF version of Repository to achieve + .UseUoW(dbOptions => dbOptions.UseSqlServer("server=localhost;uid=sa;pwd=P@ssw0rd;database=idientity")) + .UseRepository();//Use the EF version of Repository to achieve }) ``` diff --git a/src/Ddd/Masa.Contrib.Ddd.Domain/README.zh-CN.md b/src/Ddd/Masa.Contrib.Ddd.Domain/README.zh-CN.md index 1ade16ef4..f8af90b57 100644 --- a/src/Ddd/Masa.Contrib.Ddd.Domain/README.zh-CN.md +++ b/src/Ddd/Masa.Contrib.Ddd.Domain/README.zh-CN.md @@ -25,13 +25,13 @@ builder.Services options.UseIntegrationEventBus(opt => { opt.UseDapr(); - opt.UseEventLog();//使用跨进程事件 + opt.UseEventLog();//使用跨进程事件 }); options // .UseEventBus(eventBuilder => eventBuilder.UseMiddleware(typeof(ValidatorMiddleware<>))) // 使用进程内事件并使用中间件 .UseEventBus()//使用进程内事件 - .UseUoW(dbOptions => dbOptions.UseSqlServer("server=localhost;uid=sa;pwd=P@ssw0rd;database=idientity")) - .UseRepository();//使用Repository的EF版实现 + .UseUoW(dbOptions => dbOptions.UseSqlServer("server=localhost;uid=sa;pwd=P@ssw0rd;database=idientity")) + .UseRepository();//使用Repository的EF版实现 }) ``` diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents/README.md b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents/README.md index 037c4a252..fd7da4bf1 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents/README.md +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents/README.md @@ -17,14 +17,14 @@ Install-Package Masa.Contrib.Data.EntityFrameworkCore.SqlServer // Use SqlServer ``` C# builder.Services - .AddIntegrationEventBus(options=> + .AddIntegrationEventBus(options=> { options.UseDapr();//Use Dapr to provide pub/sub capabilities, or you can choose other options.UseUoW(dbOptions => dbOptions.UseSqlServer("server=localhost;uid=sa;pwd=P@ssw0rd;database=identity"))//Use unit of work, recommended; }); ``` -> CustomizeIntegrationEventLogService (custom local message service) needs to inherit IIntegrationEventLogService, and the parameters in the constructor must support getting from CI +> CustomIntegrationEventLogService (custom local message service) needs to inherit IIntegrationEventLogService, and the parameters in the constructor must support getting from CI 1.2 Use the provided EF version of the local message service diff --git a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents/README.zh-CN.md b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents/README.zh-CN.md index 8ff7f6dd4..f5f1810b2 100644 --- a/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents/README.zh-CN.md +++ b/src/Dispatcher/Masa.Contrib.Dispatcher.IntegrationEvents/README.zh-CN.md @@ -17,14 +17,14 @@ Install-Package Masa.Contrib.Data.EntityFrameworkCore.SqlServer // 使用SqlServ ```C# builder.Services - .AddIntegrationEventBus(options=> + .AddIntegrationEventBus(options=> { options.UseDapr();//使用Dapr提供pub/sub能力,也可以自行选择其他的 options.UseUoW(dbOptions => dbOptions.UseSqlServer("server=localhost;uid=sa;pwd=P@ssw0rd;database=identity"))//使用工作单元,推荐使用; }); ``` -> CustomizeIntegrationEventLogService(自定义本地消息服务)需继承IIntegrationEventLogService,并且构造函数中的参数必须支持从CI获取 +> CustomIntegrationEventLogService(自定义本地消息服务)需继承IIntegrationEventLogService,并且构造函数中的参数必须支持从CI获取 1.2 使用提供的EF版的本地消息服务 diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/CallerOptionsExtensions.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/CallerOptionsExtensions.cs index 14ae3224c..b8ec0057a 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/CallerOptionsExtensions.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/CallerOptionsExtensions.cs @@ -23,7 +23,7 @@ public static DefaultDaprClientBuilder UseDapr(this CallerOptions callerOptions, }); AddCallerExtensions.AddCaller(callerOptions, builder.Name, builder.IsDefault, - serviceProvider => new DaprCallerProvider(serviceProvider, builder.Name, builder.AppId)); + serviceProvider => new DaprCaller(serviceProvider, builder.Name, builder.AppId)); return new DefaultDaprClientBuilder(callerOptions.Services, builder.Name); } diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCallerProvider.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCaller.cs similarity index 96% rename from src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCallerProvider.cs rename to src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCaller.cs index ac8f35e23..41feb8b4f 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCallerProvider.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/DaprCaller.cs @@ -3,14 +3,14 @@ namespace Masa.Contrib.Service.Caller.DaprClient; -public class DaprCallerProvider : AbstractCallerProvider +public class DaprCaller : AbstractCaller { private Dapr.Client.DaprClient? _daprClient; private Dapr.Client.DaprClient DaprClient => _daprClient ??= ServiceProvider.GetRequiredService(); private readonly CallerDaprClientOptions _callerDaprClientOptions; protected readonly string AppId; - public DaprCallerProvider(IServiceProvider serviceProvider, string name, string appId) + public DaprCaller(IServiceProvider serviceProvider, string name, string appId) : base(serviceProvider) { var optionsFactory = serviceProvider.GetRequiredService>(); diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.md b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.md index 87eddde43..8da3bdadf 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.md +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.md @@ -27,8 +27,8 @@ Install-Package Masa.Contrib.Service.Caller.DaprClient 2. How to use: ```` C# - app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) - => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + app.MapGet("/Test/User/Hello", ([FromServices] ICaller userCaller, string name) + => userCaller.GetAsync($"/Hello", new { Name = name })); ```` > The interface address of the complete request is: http://localhost:3500/v1.0/invoke//method/Hello?Name={name} @@ -54,22 +54,22 @@ Install-Package Masa.Contrib.Service.Caller.DaprClient 4. How to use UserCaller or OrderCaller ```` C# - app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) - => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + app.MapGet("/Test/User/Hello", ([FromServices] ICaller userCaller, string name) + => userCaller.GetAsync($"/Hello", new { Name = name })); app.MapGet("/Test/Order/Hello", ([FromServices] ICallerFactory callerFactory, string name) => { - var callerProvider = callerFactory.CreateClient("OrderCaller"); - return callerProvider.GetAsync($"/Hello", new { Name = name }); + var caller = callerFactory.CreateClient("OrderCaller"); + return caller.GetAsync($"/Hello", new { Name = name }); }); ```` > When multiple Callers are added, how to get the specified Caller? ->> Get the CallerProvider of the specified alias through the `CreateClient` method of `CallerFactory` +>> Get the Caller of the specified alias through the `CreateClient` method of `CallerFactory` > -> Why doesn't `userCallerProvider` get the corresponding Caller through the `CreateClient` method of `CallerFactory`? ->> If no default ICallerProvider is specified, the default CallerProvider is the first one added in the `AddCaller` method +> Why doesn't `userCaller` get the corresponding Caller through the `CreateClient` method of `CallerFactory`? +>> If no default ICaller is specified, the default Caller is the first one added in the `AddCaller` method ### Recommended usage @@ -90,7 +90,7 @@ Install-Package Masa.Contrib.Service.Caller.DaprClient { } - public Task HelloAsync(string name) => CallerProvider.GetStringAsync($"/Hello", new { Name = name }); + public Task HelloAsync(string name) => Caller.GetStringAsync($"/Hello", new { Name = name }); } ```` diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md index 8b28e8f90..2aa8663a6 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.DaprClient/README.zh-CN.md @@ -27,8 +27,8 @@ Install-Package Masa.Contrib.Service.Caller.DaprClient 2. 如何使用: ``` C# - app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) - => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + app.MapGet("/Test/User/Hello", ([FromServices] ICaller userCaller, string name) + => userCaller.GetAsync($"/Hello", new { Name = name })); ``` > 完整请求的接口地址是:http://localhost:3500/v1.0/invoke//method/Hello?Name={name} @@ -54,22 +54,22 @@ Install-Package Masa.Contrib.Service.Caller.DaprClient 4. 如何使用UserCaller或OrderCaller ``` C# - app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) - => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + app.MapGet("/Test/User/Hello", ([FromServices] ICaller userCaller, string name) + => userCaller.GetAsync($"/Hello", new { Name = name })); app.MapGet("/Test/Order/Hello", ([FromServices] ICallerFactory callerFactory, string name) => { - var callerProvider = callerFactory.CreateClient("OrderCaller"); - return callerProvider.GetAsync($"/Hello", new { Name = name }); + var caller = callerFactory.CreateClient("OrderCaller"); + return caller.GetAsync($"/Hello", new { Name = name }); }); ``` > 当多个Caller被添加时,如何获取指定的Caller? ->> 通过`CallerFactory`的`CreateClient`方法得到指定别名的CallerProvider +>> 通过`CallerFactory`的`CreateClient`方法得到指定别名的Caller > -> 为什么`userCallerProvider`没有通过`CallerFactory`的`CreateClient`方法得到对应的Caller? ->> 如果未指定默认的ICallerProvider,则在`AddCaller`方法中第一个被添加的就是默认的CallerProvider +> 为什么`userCaller`没有通过`CallerFactory`的`CreateClient`方法得到对应的Caller? +>> 如果未指定默认的ICaller,则在`AddCaller`方法中第一个被添加的就是默认的Caller ### 推荐用法 @@ -90,7 +90,7 @@ Install-Package Masa.Contrib.Service.Caller.DaprClient { } - public Task HelloAsync(string name) => CallerProvider.GetStringAsync($"/Hello", new { Name = name }); + public Task HelloAsync(string name) => Caller.GetStringAsync($"/Hello", new { Name = name }); } ``` diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/CallerOptionsExtensions.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/CallerOptionsExtensions.cs index bf31e1ebf..c06dd2997 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/CallerOptionsExtensions.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/CallerOptionsExtensions.cs @@ -12,7 +12,7 @@ public static IHttpClientBuilder UseHttpClient(this CallerOptions callerOptions, => builder.ConfigureHttpClient(httpClient)); AddCallerExtensions.AddCaller(callerOptions, builder.Name, builder.IsDefault, serviceProvider - => new HttpClientCallerProvider(serviceProvider, builder.Name, builder.Prefix)); + => new HttpClientCaller(serviceProvider, builder.Name, builder.Prefix)); return httpClientBuilder; } diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCallerProvider.cs b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCaller.cs similarity index 94% rename from src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCallerProvider.cs rename to src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCaller.cs index 4a7647b7a..474925301 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCallerProvider.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCaller.cs @@ -3,13 +3,13 @@ namespace Masa.Contrib.Service.Caller.HttpClient; -public class HttpClientCallerProvider : AbstractCallerProvider +public class HttpClientCaller : AbstractCaller { private readonly System.Net.Http.HttpClient _httpClient; private readonly string _prefix; private readonly bool _prefixIsNullOrEmpty; - public HttpClientCallerProvider(IServiceProvider serviceProvider, string name, string prefix) + public HttpClientCaller(IServiceProvider serviceProvider, string name, string prefix) : base(serviceProvider) { _httpClient = serviceProvider.GetRequiredService().CreateClient(name); diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/Masa.Contrib.Service.Caller.HttpClient.csproj b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/Masa.Contrib.Service.Caller.HttpClient.csproj index 83d386c93..b9f47bef2 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/Masa.Contrib.Service.Caller.HttpClient.csproj +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/Masa.Contrib.Service.Caller.HttpClient.csproj @@ -7,11 +7,11 @@ - + - + diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.md b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.md index 1958c306c..8ca46a15e 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.md +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.md @@ -16,10 +16,10 @@ Install-Package Masa.Contrib.Service.Caller.HttpClient ```` C# builder.Services.AddCaller(options => { - options.UseHttpClient(httpClientBuilder => + options.UseHttpClient(clientBuilder => { - httpClientBuilder.Name = "UserCaller";// The alias of the current Caller, when there is only one HttpClient, you can not assign a value to Name - httpClientBuilder.BaseAddress = "http://localhost:5000" ; + clientBuilder.Name = "UserCaller";// The alias of the current Caller, when there is only one HttpClient, you can not assign a value to Name + clientBuilder.BaseAddress = "http://localhost:5000" ; }); }); ```` @@ -27,8 +27,8 @@ Install-Package Masa.Contrib.Service.Caller.HttpClient 2. How to use: ```` C# - app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) - => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + app.MapGet("/Test/User/Hello", ([FromServices] ICaller userCaller, string name) + => userCaller.GetAsync($"/Hello", new { Name = name })); ```` > The interface address of the complete request is: http://localhost:5000/Hello?Name={name} @@ -38,15 +38,15 @@ Install-Package Masa.Contrib.Service.Caller.HttpClient ```` C# builder.Services.AddCaller(options => { - options.UseHttpClient(httpClientBuilder => + options.UseHttpClient(clientBuilder => { - httpClientBuilder.Name = "UserCaller"; - httpClientBuilder.BaseAddress = "http://localhost:5000" ; + clientBuilder.Name = "UserCaller"; + clientBuilder.BaseAddress = "http://localhost:5000" ; }); - options.UseHttpClient(httpClientBuilder => + options.UseHttpClient(clientBuilder => { - httpClientBuilder.Name = "OrderCaller"; - httpClientBuilder.BaseAddress = "http://localhost:6000" ; + clientBuilder.Name = "OrderCaller"; + clientBuilder.BaseAddress = "http://localhost:6000" ; }); }); ```` @@ -54,22 +54,22 @@ Install-Package Masa.Contrib.Service.Caller.HttpClient 4. How to use UserCaller or OrderCaller ```` C# - app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) - => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + app.MapGet("/Test/User/Hello", ([FromServices] ICaller userCaller, string name) + => userCaller.GetAsync($"/Hello", new { Name = name })); app.MapGet("/Test/Order/Hello", ([FromServices] ICallerFactory callerFactory, string name) => { - var callerProvider = callerFactory.CreateClient("OrderCaller"); - return callerProvider.GetAsync($"/Hello", new { Name = name }); + var caller = callerFactory.Create("OrderCaller"); + return caller.GetAsync($"/Hello", new { Name = name }); }); ```` > When multiple Callers are added, how to get the specified Caller? ->> Get the CallerProvider of the specified alias through the `CreateClient` method of `CallerFactory` +>> Get the Caller of the specified alias through the `Create` method of `CallerFactory` > -> Why doesn't `userCallerProvider` get the corresponding Caller through the `CreateClient` method of `CallerFactory`? ->> If no default ICallerProvider is specified, the default CallerProvider is the first one added in the `AddCaller` method +> Why doesn't `userCaller` get the corresponding Caller through the `Create` method of `CallerFactory`? +>> If no default ICaller is specified, the default Caller is the first one added in the `AddCaller` method ### Recommended usage @@ -90,7 +90,7 @@ Install-Package Masa.Contrib.Service.Caller.HttpClient { } - public Task HelloAsync(string name) => CallerProvider.GetStringAsync($"/Hello", new { Name = name }); + public Task HelloAsync(string name) => Caller.GetStringAsync($"/Hello", new { Name = name }); /// /// There is no need to overload by default, and it can be overloaded when there are special requirements for httpClient diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md index 8d927cc12..d3781f330 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md +++ b/src/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/README.zh-CN.md @@ -16,10 +16,10 @@ Install-Package Masa.Contrib.Service.Caller.HttpClient ``` C# builder.Services.AddCaller(options => { - options.UseHttpClient(httpClientBuilder => + options.UseHttpClient(clientBuilder => { - httpClientBuilder.Name = "UserCaller";// 当前Caller的别名,仅存在一个HttpClient时,可以不对Name赋值 - httpClientBuilder.BaseAddress = "http://localhost:5000" ; + clientBuilder.Name = "UserCaller";// 当前Caller的别名,仅存在一个HttpClient时,可以不对Name赋值 + clientBuilder.BaseAddress = "http://localhost:5000" ; }); }); ``` @@ -27,8 +27,8 @@ Install-Package Masa.Contrib.Service.Caller.HttpClient 2. 如何使用: ``` C# - app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) - => userCallerProvider.GetAsync($"/Hello", new { Name = name })); + app.MapGet("/Test/User/Hello", ([FromServices] ICaller userCaller, string name) + => userCaller.GetAsync($"/Hello", new { Name = name })); ``` > 完整请求的接口地址是:http://localhost:5000/Hello?Name={name} @@ -38,15 +38,15 @@ Install-Package Masa.Contrib.Service.Caller.HttpClient ``` C# builder.Services.AddCaller(options => { - options.UseHttpClient(httpClientBuilder => + options.UseHttpClient(clientBuilder => { - httpClientBuilder.Name = "UserCaller"; - httpClientBuilder.BaseAddress = "http://localhost:5000" ; + clientBuilder.Name = "UserCaller"; + clientBuilder.BaseAddress = "http://localhost:5000" ; }); - options.UseHttpClient(httpClientBuilder => + options.UseHttpClient(clientBuilder => { - httpClientBuilder.Name = "OrderCaller"; - httpClientBuilder.BaseAddress = "http://localhost:6000" ; + clientBuilder.Name = "OrderCaller"; + clientBuilder.BaseAddress = "http://localhost:6000" ; }); }); ``` @@ -54,22 +54,22 @@ Install-Package Masa.Contrib.Service.Caller.HttpClient 4. 如何使用UserCaller或OrderCaller ``` C# - app.MapGet("/Test/User/Hello", ([FromServices] ICallerProvider userCallerProvider, string name) + app.MapGet("/Test/User/Hello", ([FromServices] ICaller userCaller, string name) => userCallerProvider.GetAsync($"/Hello", new { Name = name })); app.MapGet("/Test/Order/Hello", ([FromServices] ICallerFactory callerFactory, string name) => { - var callerProvider = callerFactory.CreateClient("OrderCaller"); - return callerProvider.GetAsync($"/Hello", new { Name = name }); + var orderCaller = callerFactory.Create("OrderCaller"); + return orderCaller.GetAsync($"/Hello", new { Name = name }); }); ``` > 当多个Caller被添加时,如何获取指定的Caller? ->> 通过`CallerFactory`的`CreateClient`方法得到指定别名的CallerProvider +>> 通过`CallerFactory`的`Create`方法得到指定别名的Caller > -> 为什么`userCallerProvider`没有通过`CallerFactory`的`CreateClient`方法得到对应的Caller? ->> 如果未指定默认的ICallerProvider,则在`AddCaller`方法中第一个被添加的就是默认的CallerProvider +> 为什么`userCaller`没有通过`CallerFactory`的`Create`方法得到对应的Caller? +>> 如果未指定默认的ICallerProvider,则在`AddCaller`方法中第一个被添加的就是默认的Caller ### 推荐用法 @@ -90,7 +90,7 @@ Install-Package Masa.Contrib.Service.Caller.HttpClient { } - public Task HelloAsync(string name) => CallerProvider.GetStringAsync($"/Hello", new { Name = name }); + public Task HelloAsync(string name) => Caller.GetStringAsync($"/Hello", new { Name = name }); /// /// 默认不需要重载,对httpClient有特殊需求时可重载 diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultCallerFactory.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultCallerFactory.cs index 251c826de..b322c34fa 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultCallerFactory.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultCallerFactory.cs @@ -14,13 +14,13 @@ public DefaultCallerFactory(IServiceProvider serviceProvider, IOptions c.IsDefault) ?? _callers.FirstOrDefault()!; return caller.Func.Invoke(_serviceProvider); } - public ICallerProvider CreateClient(string name) + public ICaller Create(string name) { var caller = _callers.SingleOrDefault(c => c.Name == name); if (caller == null) diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultTypeConvertProvider.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultTypeConvert.cs similarity index 98% rename from src/Service/Caller/Masa.Contrib.Service.Caller/DefaultTypeConvertProvider.cs rename to src/Service/Caller/Masa.Contrib.Service.Caller/DefaultTypeConvert.cs index e23dd14f5..b687ac8df 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultTypeConvertProvider.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultTypeConvert.cs @@ -3,7 +3,7 @@ namespace Masa.Contrib.Service.Caller; -public class DefaultTypeConvertProvider : ITypeConvertProvider +public class DefaultTypeConvert : ITypeConvert { private static readonly ConcurrentDictionary> Dictionary = new(); diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/Internal/XmlUtils.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/Internal/XmlUtils.cs new file mode 100644 index 000000000..20f857473 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/Internal/XmlUtils.cs @@ -0,0 +1,26 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller.Internal; + +/// +/// Temporary use, later versions will be removed +/// +internal class XmlUtils +{ + public static string Serializer(object data) + { + MemoryStream ms = new MemoryStream(); + StreamWriter sw = new StreamWriter(ms, Encoding.UTF8); + XmlSerializer xz = new XmlSerializer(data.GetType()); + xz.Serialize(sw, data); + return Encoding.UTF8.GetString(ms.ToArray()); + } + + public static T Deserialize(string xml) + { + XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); + using MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml.ToCharArray())); + return (T)xmlSerializer.Deserialize(stream)!; + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/README.md b/src/Service/Caller/Masa.Contrib.Service.Caller/README.md index 1c986b0c2..f4fc126e3 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/README.md +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/README.md @@ -4,11 +4,11 @@ Masa.Contrib.Service.Caller is the basic class library of Caller, which provides the abstraction of the following capabilities -* `ICallerFactory`: Factory for creating `CallerProvider` (Singleton) -* `ICallerProvider`: Provides `Post`, `Delete`, `Patch`, `Put`, `Get`, `Send` capabilities (Scoped) +* `ICallerFactory`: Factory for creating `Caller` (Singleton) +* `ICaller`: Provides `Post`, `Delete`, `Patch`, `Put`, `Get`, `Send` capabilities (Scoped) * `IRequestMessage`: Provides the ability to process request data (default implementation [`JsonRequestMessage`](./JsonRequestMessage.cs)) (Singleton) * `IResponseMessage`: Provides the ability to handle response data (default implementation [`DefaultResponseMessage`](./DefaultResponseMessage.cs)) (Singleton) -* `ITypeConvertProvider`: Provides the ability to convert types, support for `Get` requests of `ICallerProvider` (Singleton) +* `ITypeConvert`: Provides the ability to convert types, support for `Get` requests of `ICaller` (Singleton) ## Summarize @@ -31,6 +31,6 @@ Masa.Contrib.Service.Caller is the basic class library of Caller, which provides > A: Rewrite IResponseMessage, add custom ResponseMessage to IServiceCollection before calling AddCaller ```` C# - services.AddSingleton(); + services.AddSingleton(); services.AddCaller(); ```` \ No newline at end of file diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/README.zh-CN.md b/src/Service/Caller/Masa.Contrib.Service.Caller/README.zh-CN.md index c90e74f30..5869797a5 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/README.zh-CN.md +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/README.zh-CN.md @@ -4,11 +4,11 @@ Masa.Contrib.Service.Caller是Caller的基础类库,提供了以下能力的抽象 -* `ICallerFactory`: 工厂,用于创建`CallerProvider` (Singleton) -* `ICallerProvider`: 提供`Post`、`Delete`、`Patch`、`Put`、`Get`、`Send`的能力 (Scoped) +* `ICallerFactory`: 工厂,用于创建`Caller` (Singleton) +* `ICaller`: 提供`Post`、`Delete`、`Patch`、`Put`、`Get`、`Send`的能力 (Scoped) * `IRequestMessage`: 提供对请求数据处理的能力 (默认实现[`JsonRequestMessage`](./JsonRequestMessage.cs)) (Singleton) * `IResponseMessage`: 提供对响应数据处理的能力 (默认实现[`DefaultResponseMessage`](./DefaultResponseMessage.cs)) (Singleton) -* `ITypeConvertProvider`: 提供类型转换的能力,为`ICallerProvider`的`Get`请求支撑 (Singleton) +* `ITypeConvert`: 提供类型转换的能力,为`ICaller`的`Get`请求支撑 (Singleton) ## 总结 @@ -31,6 +31,6 @@ Masa.Contrib.Service.Caller是Caller的基础类库,提供了以下能力的 > A: 重写IResponseMessage,在调用AddCaller之前先将自定义的ResponseMessage添加到IServiceCollection中 ``` C# - services.AddSingleton(); + services.AddSingleton(); services.AddCaller(); ``` \ No newline at end of file diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/ServiceCollectionExtensions.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/ServiceCollectionExtensions.cs index eae0fee63..80232d9da 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/ServiceCollectionExtensions.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/ServiceCollectionExtensions.cs @@ -29,9 +29,9 @@ public static IServiceCollection AddCaller(this IServiceCollection services, Act services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddScoped(serviceProvider => serviceProvider.GetRequiredService().CreateClient()); + services.TryAddScoped(serviceProvider => serviceProvider.GetRequiredService().Create()); - services.TryAddSingleton(); + services.TryAddSingleton(); services.AddAutomaticCaller(callerOption); TryOrUpdateCallerOptions(services, callerOption); return services; diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/XmlRequestMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/XmlRequestMessage.cs new file mode 100644 index 000000000..e8e02e261 --- /dev/null +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/XmlRequestMessage.cs @@ -0,0 +1,28 @@ +// Copyright (c) MASA Stack All rights reserved. +// Licensed under the MIT License. See LICENSE.txt in the project root for license information. + +namespace Masa.Contrib.Service.Caller; + +public class XmlRequestMessage : DefaultRequestMessage, IRequestMessage +{ + public XmlRequestMessage( + IOptions options, + IRequestIdGenerator requestIdGenerator, + IHttpContextAccessor? httpContextAccessor = null) + : base(options, requestIdGenerator, httpContextAccessor) + { + } + + public Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage) + { + TrySetRequestId(requestMessage); + return Task.FromResult(requestMessage); + } + + public async Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage, TRequest data) + { + requestMessage = await ProcessHttpRequestMessageAsync(requestMessage); + requestMessage.Content = new StringContent(XmlUtils.Serializer(data!)); + return requestMessage; + } +} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/_Imports.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/_Imports.cs index e936bf497..8b5980904 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/_Imports.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/_Imports.cs @@ -18,3 +18,5 @@ global using System.Runtime.ExceptionServices; global using System.Text.Json; global using System.Text.Json.Serialization; +global using System.Text; +global using System.Xml.Serialization; diff --git a/src/Service/Masa.Contrib.Service.MinimalAPIs/README.md b/src/Service/Masa.Contrib.Service.MinimalAPIs/README.md index 54a68bbbb..08c62d7ce 100644 --- a/src/Service/Masa.Contrib.Service.MinimalAPIs/README.md +++ b/src/Service/Masa.Contrib.Service.MinimalAPIs/README.md @@ -25,7 +25,7 @@ var app = builder.Services .AddServices(builder); ``` -2. Customize Service and inherit ServiceBase +2. Custom Service and inherit ServiceBase ```c# public class IntegrationEventService : ServiceBase diff --git a/test/Masa.Contrib.BasicAbility.Auth.Tests/PermissionServiceTest.cs b/test/Masa.Contrib.BasicAbility.Auth.Tests/PermissionServiceTest.cs index 8d11d3405..7481c8c59 100644 --- a/test/Masa.Contrib.BasicAbility.Auth.Tests/PermissionServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Auth.Tests/PermissionServiceTest.cs @@ -13,11 +13,11 @@ public async Task TestGetMenusAsync(string appId) var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); var data = new List(); var requestUri = $"api/permission/menus?appId={appId}&userId={userId}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var permissionService = new PermissionService(callerProvider.Object, userContext.Object); + var permissionService = new PermissionService(caller.Object, userContext.Object); var result = await permissionService.GetMenusAsync(appId); userContext.Verify(user => user.GetUserId(), Times.Once); Assert.IsTrue(result is not null); @@ -30,13 +30,13 @@ public async Task TestAuthorizedAsync(string appId, string code) var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); var data = false; var requestUri = $"api/permission/authorized?code={code}&userId={userId}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var permissionService = new PermissionService(callerProvider.Object, userContext.Object); + var permissionService = new PermissionService(caller.Object, userContext.Object); var result = await permissionService.AuthorizedAsync(appId, code); - callerProvider.Verify(provider => provider.GetAsync(It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync(It.IsAny(), default), Times.Once); } [TestMethod] @@ -46,13 +46,13 @@ public async Task TestGetElementPermissionsAsync(string appId) var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); var data = new List(); var requestUri = $"api/permission/element-permissions?appId={appId}&userId={userId}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var permissionService = new PermissionService(callerProvider.Object, userContext.Object); + var permissionService = new PermissionService(caller.Object, userContext.Object); var result = await permissionService.GetElementPermissionsAsync(appId); - callerProvider.Verify(provider => provider.GetAsync>(It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync>(It.IsAny(), default), Times.Once); Assert.IsTrue(result is not null); } @@ -63,13 +63,13 @@ public async Task TestGetFavoriteMenuListAsync(string menuId) var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); var data = new List(); var requestUri = $"api/permission/menu-favorite-list?userId={userId}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var permissionService = new PermissionService(callerProvider.Object, userContext.Object); + var permissionService = new PermissionService(caller.Object, userContext.Object); var result = await permissionService.GetFavoriteMenuListAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result is not null); } @@ -79,13 +79,13 @@ public async Task TestAddFavoriteMenuAsync(string menuId) { var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); var requestUri = $"api/permission/addFavoriteMenu?permissionId={Guid.Parse(menuId)}&userId={userId}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PutAsync(requestUri, null, true, default)).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.PutAsync(requestUri, null, true, default)).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var permissionService = new PermissionService(callerProvider.Object, userContext.Object); + var permissionService = new PermissionService(caller.Object, userContext.Object); var result = await permissionService.AddFavoriteMenuAsync(Guid.Parse(menuId)); - callerProvider.Verify(provider => provider.PutAsync(requestUri, null, true, default), Times.Once); + caller.Verify(provider => provider.PutAsync(requestUri, null, true, default), Times.Once); Assert.IsTrue(result); } @@ -95,13 +95,13 @@ public async Task TestRemoveFavoriteMenuAsync(string menuId) { var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); var requestUri = $"api/permission/removeFavoriteMenu?permissionId={Guid.Parse(menuId)}&userId={userId}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PutAsync(requestUri, null, true, default)).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.PutAsync(requestUri, null, true, default)).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var permissionService = new PermissionService(callerProvider.Object, userContext.Object); + var permissionService = new PermissionService(caller.Object, userContext.Object); var result = await permissionService.RemoveFavoriteMenuAsync(Guid.Parse(menuId)); - callerProvider.Verify(provider => provider.PutAsync(requestUri, null, true, default), Times.Once); + caller.Verify(provider => provider.PutAsync(requestUri, null, true, default), Times.Once); Assert.IsTrue(result); } } diff --git a/test/Masa.Contrib.BasicAbility.Auth.Tests/ProjectServiceTest.cs b/test/Masa.Contrib.BasicAbility.Auth.Tests/ProjectServiceTest.cs index 15076385a..54ad837a8 100644 --- a/test/Masa.Contrib.BasicAbility.Auth.Tests/ProjectServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Auth.Tests/ProjectServiceTest.cs @@ -15,14 +15,14 @@ public async Task TestGetGlobalNavigationsAsync() }; var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); var requestUri = $"api/project/navigations?userId={userId}&environment=development"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); userContext.SetupGet(user => user.Environment).Returns("development"); - var projectService = new Mock(callerProvider.Object, userContext.Object); + var projectService = new Mock(caller.Object, userContext.Object); var result = await projectService.Object.GetGlobalNavigations(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 1); } } diff --git a/test/Masa.Contrib.BasicAbility.Auth.Tests/SubjectServiceTest.cs b/test/Masa.Contrib.BasicAbility.Auth.Tests/SubjectServiceTest.cs index d77b9e020..c349f6cae 100644 --- a/test/Masa.Contrib.BasicAbility.Auth.Tests/SubjectServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Auth.Tests/SubjectServiceTest.cs @@ -15,11 +15,11 @@ public async Task TestGetListAsync() }; string filter = "test"; var requestUri = $"api/subject/getList"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var subjectService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var subjectService = new Mock(caller.Object); var result = await subjectService.Object.GetListAsync(filter); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result.Count == 1); } } diff --git a/test/Masa.Contrib.BasicAbility.Auth.Tests/TeamServiceTest.cs b/test/Masa.Contrib.BasicAbility.Auth.Tests/TeamServiceTest.cs index d2ede4b6c..92a6b8c1e 100644 --- a/test/Masa.Contrib.BasicAbility.Auth.Tests/TeamServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Auth.Tests/TeamServiceTest.cs @@ -12,12 +12,12 @@ public async Task TestGetDetailAsync() var data = new TeamDetailModel(); Guid teamId = Guid.NewGuid(); var requestUri = $"api/team/detail"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var teamService = new Mock(callerProvider.Object, userContext.Object); + var teamService = new Mock(caller.Object, userContext.Object); var result = await teamService.Object.GetDetailAsync(teamId); - callerProvider.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result is not null); } @@ -26,12 +26,12 @@ public async Task TestGetAllAsync() { var data = new List(); var requestUri = $"api/team/list"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var teamService = new Mock(callerProvider.Object, userContext.Object); + var teamService = new Mock(caller.Object, userContext.Object); var result = await teamService.Object.GetAllAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result is not null); } @@ -41,13 +41,13 @@ public async Task TestGetUserTeamsAsync() var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); var data = new List(); var requestUri = $"api/team/list?userId={userId}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var teamService = new Mock(callerProvider.Object, userContext.Object); + var teamService = new Mock(caller.Object, userContext.Object); var result = await teamService.Object.GetUserTeamsAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result is not null); } } diff --git a/test/Masa.Contrib.BasicAbility.Auth.Tests/UserServiceTest.cs b/test/Masa.Contrib.BasicAbility.Auth.Tests/UserServiceTest.cs index 23bb3a8e1..4701919c4 100644 --- a/test/Masa.Contrib.BasicAbility.Auth.Tests/UserServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Auth.Tests/UserServiceTest.cs @@ -12,12 +12,12 @@ public async Task TestAddAsync() var addUser = new AddUserModel(); var user = new UserModel(); var requestUri = $"api/user/addExternal"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, addUser, default)).ReturnsAsync(user).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync(requestUri, addUser, default)).ReturnsAsync(user).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.AddAsync(addUser); - callerProvider.Verify(provider => provider.PostAsync(requestUri, addUser, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, addUser, default), Times.Once); Assert.IsTrue(result is not null); } @@ -27,12 +27,12 @@ public async Task UpsertAsync() var upsertUser = new UpsertUserModel(); var user = new UserModel(); var requestUri = $"api/user/upsertExternal"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, upsertUser, default)).ReturnsAsync(user).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync(requestUri, upsertUser, default)).ReturnsAsync(user).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.UpsertAsync(upsertUser); - callerProvider.Verify(provider => provider.PostAsync(requestUri, upsertUser, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, upsertUser, default), Times.Once); Assert.IsTrue(result is not null); } @@ -45,12 +45,12 @@ public async Task TestGetListByDepartmentAsync() }; Guid departmentId = Guid.NewGuid(); var requestUri = $"api/staff/getListByDepartment"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.GetListByDepartmentAsync(departmentId); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -63,12 +63,12 @@ public async Task TestGetListByTeamAsync() }; Guid teamId = Guid.NewGuid(); var requestUri = $"api/staff/getListByTeam"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.GetListByTeamAsync(teamId); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -81,12 +81,12 @@ public async Task TestGetListByRoleAsync() }; Guid roleId = Guid.NewGuid(); var requestUri = $"api/staff/getListByRole"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.GetListByRoleAsync(roleId); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -96,12 +96,12 @@ public async Task TestGetTotalByDepartmentAsync() long data = 10; Guid departmentId = Guid.NewGuid(); var requestUri = $"api/staff/getTotalByDepartment"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.GetTotalByDepartmentAsync(departmentId); - callerProvider.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result == data); } @@ -111,12 +111,12 @@ public async Task TestGetTotalByByRoleAsync() long data = 10; Guid roleId = Guid.NewGuid(); var requestUri = $"api/staff/getTotalByRole"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.GetTotalByRoleAsync(roleId); - callerProvider.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result == data); } @@ -126,12 +126,12 @@ public async Task TestGetTotalByTeamAsync() long data = 10; Guid teamId = Guid.NewGuid(); var requestUri = $"api/staff/getTotalByTeam"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.GetTotalByTeamAsync(teamId); - callerProvider.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result == data); } @@ -142,12 +142,12 @@ public async Task TestValidateCredentialsByAccountAsync(string account, string p var data = false; Guid departmentId = Guid.NewGuid(); var requestUri = $"api/user/validateByAccount"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.ValidateCredentialsByAccountAsync(account, password); - callerProvider.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), default), Times.Once); } [TestMethod] @@ -156,12 +156,12 @@ public async Task TestFindByAccountAsync(string account) { var data = new UserModel(); var requestUri = $"api/user/findByAccount"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.FindByAccountAsync(account); - callerProvider.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result is not null); } @@ -174,12 +174,12 @@ public async Task TestFindByPhoneNumberAsync(string phoneNumber) PhoneNumber = phoneNumber }; var requestUri = $"api/user/findByPhoneNumber"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.FindByPhoneNumberAsync(phoneNumber); - callerProvider.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result is not null && result.PhoneNumber == data.PhoneNumber); } @@ -189,12 +189,12 @@ public async Task TestFindByEmailAsync(string email) { var data = new UserModel(); var requestUri = $"api/user/findByEmail"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.FindByEmailAsync(email); - callerProvider.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result is not null && result.Email == data.Email); } @@ -204,13 +204,13 @@ public async Task TestGetCurrentUserAsync() var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); var data = new UserModel(); var requestUri = $"api/user/findById"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.GetCurrentUserAsync(); - callerProvider.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result is not null); } @@ -220,13 +220,13 @@ public async Task TestVisitedAsync(string url) { var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); var requestUri = $"api/user/visit"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, new { UserId = userId, Url = url }, true, default)).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync(requestUri, new { UserId = userId, Url = url }, true, default)).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); await userService.VisitedAsync(url); - callerProvider.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), true, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), true, default), Times.Once); } [TestMethod] @@ -241,13 +241,13 @@ public async Task TestGetVisitedListAsync() } }; var requestUri = $"api/user/visitedList"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.GetVisitedListAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -261,12 +261,12 @@ public async Task TestUpdatePasswordAsync() OldPassword = "masa123" }; var requestUri = $"api/user/updatePassword"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PutAsync(requestUri, user, true, default)).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.PutAsync(requestUri, user, true, default)).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); await userService.UpdatePasswordAsync(user); - callerProvider.Verify(provider => provider.PutAsync(requestUri, user, true, default), Times.Once); + caller.Verify(provider => provider.PutAsync(requestUri, user, true, default), Times.Once); } [TestMethod] @@ -274,12 +274,12 @@ public async Task TestDisableUserAsync() { var user = new DisableUserModel("account"); var requestUri = $"api/user/disable"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PutAsync(requestUri, user, default)).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.PutAsync(requestUri, user, default)).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); await userService.DisableUserAsync(user); - callerProvider.Verify(provider => provider.PutAsync(requestUri, user, default), Times.Once); + caller.Verify(provider => provider.PutAsync(requestUri, user, default), Times.Once); } [TestMethod] @@ -293,12 +293,12 @@ public async Task TestUpdateBasicInfoAsync() PhoneNumber = "15168440403" }; var requestUri = $"api/user/updateBasicInfo"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PutAsync(requestUri, user, true, default)).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.PutAsync(requestUri, user, true, default)).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); await userService.UpdateBasicInfoAsync(user); - callerProvider.Verify(provider => provider.PutAsync(requestUri, user, true, default), Times.Once); + caller.Verify(provider => provider.PutAsync(requestUri, user, true, default), Times.Once); } [TestMethod] @@ -316,13 +316,13 @@ public async Task GetUserPortraitsAsync() } }; var requestUri = $"api/user/portraits"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync>(requestUri, new Guid[] { userId }, default)) + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync>(requestUri, new Guid[] { userId }, default)) .ReturnsAsync(userPortraits).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var data = await userService.GetUserPortraitsAsync(userId); - callerProvider.Verify(provider => provider.PostAsync>(requestUri, new Guid[] { userId }, default), Times.Once); + caller.Verify(provider => provider.PostAsync>(requestUri, new Guid[] { userId }, default), Times.Once); Assert.IsTrue(data.Count == 1); } @@ -333,12 +333,12 @@ public async Task TestIntGetUserSystemDataAsync(string systemId) var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); var data = 1; var requestUri = $"api/user/GetUserSystemData"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)) + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)) .ReturnsAsync(data.ToString()).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.GetUserSystemDataAsync(systemId); Assert.IsTrue(result == 1); } @@ -354,12 +354,12 @@ public async Task TestObjectGetUserSystemDataAsync(string systemId) Value = "value" }; var requestUri = $"api/user/GetUserSystemData"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)) + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)) .ReturnsAsync(JsonSerializer.Serialize(data)).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.GetUserSystemDataAsync(systemId); Assert.IsTrue(result is not null); } @@ -372,13 +372,13 @@ public async Task TestIntSaveUserSystemDataAsync(string systemId) var requestUri = $"api/user/UserSystemData"; var value = 1; var data = new { UserId = userId, SystemId = systemId, Data = JsonSerializer.Serialize(value) }; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, data, true, default)).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync(requestUri, data, true, default)).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); await userService.SaveUserSystemDataAsync(systemId, value); - callerProvider.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), true, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), true, default), Times.Once); } [TestMethod] @@ -393,13 +393,13 @@ public async Task TestObjectSaveUserSystemDataAsync(string systemId) Value = "value" }; var data = new { UserId = userId, SystemId = systemId, Data = JsonSerializer.Serialize(value) }; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, data, true, default)).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync(requestUri, data, true, default)).Verifiable(); var userContext = new Mock(); userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); await userService.SaveUserSystemDataAsync(systemId, value); - callerProvider.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), true, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), true, default), Times.Once); } [TestMethod] @@ -411,12 +411,12 @@ public async Task TestGetListByAccountAsync() }; var accounts = new List { "account" }; var requestUri = $"api/user/GetListByAccount"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); var userContext = new Mock(); - var userService = new UserService(callerProvider.Object, userContext.Object); + var userService = new UserService(caller.Object, userContext.Object); var result = await userService.GetListByAccountAsync(accounts); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); Assert.IsTrue(result.Count == 1); } } diff --git a/test/Masa.Contrib.BasicAbility.Mc.Tests/ChannelServiceTest.cs b/test/Masa.Contrib.BasicAbility.Mc.Tests/ChannelServiceTest.cs index 4fd23e9ba..f207e8df2 100644 --- a/test/Masa.Contrib.BasicAbility.Mc.Tests/ChannelServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Mc.Tests/ChannelServiceTest.cs @@ -12,11 +12,11 @@ public async Task TestGetAsync() var data = new ChannelModel(); Guid channelId = Guid.NewGuid(); var requestUri = $"api/channel/{channelId}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var channelService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); + var channelService = new Mock(caller.Object); var result = await channelService.Object.GetAsync(channelId); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsTrue(result is not null); } @@ -26,11 +26,11 @@ public async Task TestGetListAsync() var options = new GetChannelModel(); var data = new PaginatedListModel(); var requestUri = $"api/channel"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); - var channelService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); + var channelService = new Mock(caller.Object); var result = await channelService.Object.GetListAsync(options); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); Assert.IsTrue(result is not null); } } diff --git a/test/Masa.Contrib.BasicAbility.Mc.Tests/MessageTaskServiceTest.cs b/test/Masa.Contrib.BasicAbility.Mc.Tests/MessageTaskServiceTest.cs index e2f25e371..a2065da62 100644 --- a/test/Masa.Contrib.BasicAbility.Mc.Tests/MessageTaskServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Mc.Tests/MessageTaskServiceTest.cs @@ -12,11 +12,11 @@ public async Task TestGetAsync() var data = new MessageTaskModel(); Guid id = Guid.NewGuid(); var requestUri = $"api/message-task/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var messageTaskService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); + var messageTaskService = new Mock(caller.Object); var result = await messageTaskService.Object.GetAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsTrue(result is not null); } @@ -25,11 +25,11 @@ public async Task TestSendOrdinaryMessageAsync() { var options = new SendOrdinaryMessageModel(); var requestUri = $"api/message-task/SendOrdinaryMessage"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); - var messageTaskService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); + var messageTaskService = new Mock(caller.Object); await messageTaskService.Object.SendOrdinaryMessageAsync(options); - callerProvider.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); } [TestMethod] @@ -37,10 +37,10 @@ public async Task TestSendTemplateMessageAsync() { var options = new SendTemplateMessageModel(); var requestUri = $"api/message-task/SendTemplateMessage"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); - var messageTaskService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); + var messageTaskService = new Mock(caller.Object); await messageTaskService.Object.SendTemplateMessageAsync(options); - callerProvider.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); } } diff --git a/test/Masa.Contrib.BasicAbility.Mc.Tests/MessageTemplateServiceTest.cs b/test/Masa.Contrib.BasicAbility.Mc.Tests/MessageTemplateServiceTest.cs index 85aee36d3..24a4912ba 100644 --- a/test/Masa.Contrib.BasicAbility.Mc.Tests/MessageTemplateServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Mc.Tests/MessageTemplateServiceTest.cs @@ -12,11 +12,11 @@ public async Task TestGetAsync() var data = new MessageTemplateModel(); Guid id = Guid.NewGuid(); var requestUri = $"api/message-template/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var messageTemplateService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); + var messageTemplateService = new Mock(caller.Object); var result = await messageTemplateService.Object.GetAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsTrue(result is not null); } @@ -26,11 +26,11 @@ public async Task TestGetListAsync() var options = new GetMessageTemplateModel(); var data = new PaginatedListModel(); var requestUri = $"api/message-template"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); - var messageTemplateService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); + var messageTemplateService = new Mock(caller.Object); var result = await messageTemplateService.Object.GetListAsync(options); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); Assert.IsTrue(result is not null); } } diff --git a/test/Masa.Contrib.BasicAbility.Mc.Tests/ReceiverGroupServiceTest.cs b/test/Masa.Contrib.BasicAbility.Mc.Tests/ReceiverGroupServiceTest.cs index 50be6cad0..de41dafdc 100644 --- a/test/Masa.Contrib.BasicAbility.Mc.Tests/ReceiverGroupServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Mc.Tests/ReceiverGroupServiceTest.cs @@ -12,11 +12,11 @@ public async Task TestGetAsync() var data = new ReceiverGroupModel(); Guid id = Guid.NewGuid(); var requestUri = $"api/receiver-group/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var receiverGroupService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); + var receiverGroupService = new Mock(caller.Object); var result = await receiverGroupService.Object.GetAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsTrue(result is not null); } @@ -26,11 +26,11 @@ public async Task TestGetListAsync() var options = new GetReceiverGroupModel(); var data = new PaginatedListModel(); var requestUri = $"api/receiver-group"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); - var receiverGroupService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); + var receiverGroupService = new Mock(caller.Object); var result = await receiverGroupService.Object.GetListAsync(options); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); Assert.IsTrue(result is not null); } } diff --git a/test/Masa.Contrib.BasicAbility.Mc.Tests/WebsiteMessageServiceTest.cs b/test/Masa.Contrib.BasicAbility.Mc.Tests/WebsiteMessageServiceTest.cs index 8a2a7035e..6db943d29 100644 --- a/test/Masa.Contrib.BasicAbility.Mc.Tests/WebsiteMessageServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Mc.Tests/WebsiteMessageServiceTest.cs @@ -12,11 +12,11 @@ public async Task TestGetAsync() var data = new WebsiteMessageModel(); Guid id = Guid.NewGuid(); var requestUri = $"api/website-message/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var websiteMessageService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); + var websiteMessageService = new Mock(caller.Object); var result = await websiteMessageService.Object.GetAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsTrue(result is not null); } @@ -26,11 +26,11 @@ public async Task TestGetListAsync() var options = new GetWebsiteMessageModel(); var data = new PaginatedListModel(); var requestUri = $"api/website-message"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); - var websiteMessageService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); + var websiteMessageService = new Mock(caller.Object); var result = await websiteMessageService.Object.GetListAsync(options); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); Assert.IsTrue(result is not null); } @@ -38,11 +38,11 @@ public async Task TestGetListAsync() public async Task TestCheckAsync() { var requestUri = $"api/website-message/Check"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, null, true, default)).Verifiable(); - var websiteMessageService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync(requestUri, null, true, default)).Verifiable(); + var websiteMessageService = new Mock(caller.Object); await websiteMessageService.Object.CheckAsync(); - callerProvider.Verify(provider => provider.PostAsync(requestUri, null, true, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, null, true, default), Times.Once); } [TestMethod] @@ -50,11 +50,11 @@ public async Task TestDeleteAsync() { Guid id = Guid.NewGuid(); var requestUri = $"api/website-message/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.DeleteAsync(requestUri, null, true, default)).Verifiable(); - var websiteMessageService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.DeleteAsync(requestUri, null, true, default)).Verifiable(); + var websiteMessageService = new Mock(caller.Object); await websiteMessageService.Object.DeleteAsync(id); - callerProvider.Verify(provider => provider.DeleteAsync(requestUri, null, true, default), Times.Once); + caller.Verify(provider => provider.DeleteAsync(requestUri, null, true, default), Times.Once); } [TestMethod] @@ -62,11 +62,11 @@ public async Task TestGetChannelListAsync() { var data = new List(); var requestUri = $"api/website-message/GetChannelList"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var websiteMessageService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var websiteMessageService = new Mock(caller.Object); var result = await websiteMessageService.Object.GetChannelListAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result is not null); } @@ -76,11 +76,11 @@ public async Task TestGetNoticeListAsync() var options = new GetNoticeListModel(); var data = new List(); var requestUri = $"api/website-message/GetNoticeList"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); - var websiteMessageService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); + var websiteMessageService = new Mock(caller.Object); var result = await websiteMessageService.Object.GetNoticeListAsync(options); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); Assert.IsTrue(result is not null); } @@ -89,11 +89,11 @@ public async Task TestReadAsync() { var options = new ReadWebsiteMessageModel(); var requestUri = $"api/website-message/Read"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); - var websiteMessageService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); + var websiteMessageService = new Mock(caller.Object); await websiteMessageService.Object.ReadAsync(options); - callerProvider.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); } [TestMethod] @@ -101,10 +101,10 @@ public async Task TestSetAllReadAsync() { var options = new ReadAllWebsiteMessageModel(); var requestUri = $"api/website-message/SetAllRead"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); - var websiteMessageService = new Mock(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); + var websiteMessageService = new Mock(caller.Object); await websiteMessageService.Object.SetAllReadAsync(options); - callerProvider.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); } } diff --git a/test/Masa.Contrib.BasicAbility.Pm.Tests/AppServiceTest.cs b/test/Masa.Contrib.BasicAbility.Pm.Tests/AppServiceTest.cs index 82c1c9a9c..6ef7f6baf 100644 --- a/test/Masa.Contrib.BasicAbility.Pm.Tests/AppServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Pm.Tests/AppServiceTest.cs @@ -13,12 +13,12 @@ public async Task TestGetAsync(int id) var data = new AppDetailModel(); var requestUri = $"api/v1/app/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.AppService.GetAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -30,12 +30,12 @@ public async Task TestGet1Async(int id) AppDetailModel? data = null; var requestUri = $"api/v1/app/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.AppService.GetAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -47,12 +47,12 @@ public async Task TestGetByIdentityAsync(string identity) var data = new AppDetailModel(); var requestUri = $"open-api/app/{identity}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.AppService.GetByIdentityAsync(identity); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -64,12 +64,12 @@ public async Task TestGetByIdentity1Async(string identity) AppDetailModel? data = null; var requestUri = $"open-api/app/{identity}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.AppService.GetByIdentityAsync(identity); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -83,12 +83,12 @@ public async Task TestGetListAsync() }; var requestUri = $"api/v1/app"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.AppService.GetListAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -99,12 +99,12 @@ public async Task TestGetList1Async() List? data = null; var requestUri = $"api/v1/app"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.AppService.GetListAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 0); } @@ -119,12 +119,12 @@ public async Task TestGetListByProjectIdsAsync() var projectIds = new List { 1 }; var requestUri = $"api/v1/projects/app"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync, List>(requestUri, projectIds, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync, List>(requestUri, projectIds, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.AppService.GetListByProjectIdsAsync(projectIds); - callerProvider.Verify(provider => provider.PostAsync, List>(requestUri, projectIds, default), Times.Once); + caller.Verify(provider => provider.PostAsync, List>(requestUri, projectIds, default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -136,12 +136,12 @@ public async Task TestGetListByProjectIds1Async() var projectIds = new List { 1 }; var requestUri = $"api/v1/projects/app"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync, List>(It.IsAny(), projectIds, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync, List>(It.IsAny(), projectIds, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.AppService.GetListByProjectIdsAsync(projectIds); - callerProvider.Verify(provider => provider.PostAsync, List>(requestUri, projectIds, default), Times.Once); + caller.Verify(provider => provider.PostAsync, List>(requestUri, projectIds, default), Times.Once); Assert.IsTrue(result.Count == 0); } @@ -153,12 +153,12 @@ public async Task TestGetWithEnvironmentClusterAsync(int id) var data = new AppDetailModel(); var requestUri = $"api/v1/appWhitEnvCluster/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.AppService.GetWithEnvironmentClusterAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -170,12 +170,12 @@ public async Task TestGetWithEnvironmentCluster1Async(int id) AppDetailModel? data = null; var requestUri = $"api/v1/appWhitEnvCluster/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.AppService.GetWithEnvironmentClusterAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } diff --git a/test/Masa.Contrib.BasicAbility.Pm.Tests/ClusterServiceTest.cs b/test/Masa.Contrib.BasicAbility.Pm.Tests/ClusterServiceTest.cs index 885a9618b..f69ec23df 100644 --- a/test/Masa.Contrib.BasicAbility.Pm.Tests/ClusterServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Pm.Tests/ClusterServiceTest.cs @@ -13,12 +13,12 @@ public async Task TestGetAsync(int id) var data = new ClusterDetailModel(); var requestUri = $"api/v1/cluster/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ClusterService.GetAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -30,12 +30,12 @@ public async Task TestGetAsync1(int id) ClusterDetailModel? data = null; var requestUri = $"api/v1/cluster/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ClusterService.GetAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -49,12 +49,12 @@ public async Task TestGetEnvironmentClustersAsync() }; var requestUri = $"api/v1/envClusters"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ClusterService.GetEnvironmentClustersAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -65,12 +65,12 @@ public async Task TestGetEnvironmentClusters1Async() List? data = null; var requestUri = $"api/v1/envClusters"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ClusterService.GetEnvironmentClustersAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 0); } @@ -84,12 +84,12 @@ public async Task TestGetListAsync() }; var requestUri = $"api/v1/cluster"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ClusterService.GetListAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -100,12 +100,12 @@ public async Task TestGetList1Async() List? data = null; var requestUri = $"api/v1/cluster"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ClusterService.GetListAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 0); } @@ -120,12 +120,12 @@ public async Task TestGetListByEnvIdAsync(int envId) }; var requestUri = $"api/v1/{envId}/cluster"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ClusterService.GetListByEnvIdAsync(envId); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -137,12 +137,12 @@ public async Task TestGetListByEnvId1Async(int envId) List? data = null; var requestUri = $"api/v1/{envId}/cluster"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ClusterService.GetListByEnvIdAsync(envId); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 0); } diff --git a/test/Masa.Contrib.BasicAbility.Pm.Tests/EnvironmentServiceTest.cs b/test/Masa.Contrib.BasicAbility.Pm.Tests/EnvironmentServiceTest.cs index c1fc184e0..f56084506 100644 --- a/test/Masa.Contrib.BasicAbility.Pm.Tests/EnvironmentServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Pm.Tests/EnvironmentServiceTest.cs @@ -13,12 +13,12 @@ public async Task TestGetAsync(int id) var data = new EnvironmentDetailModel(); var requestUri = $"api/v1/env/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default).Result).Returns(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default).Result).Returns(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.EnvironmentService.GetAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -30,12 +30,12 @@ public async Task TestGet1Async(int id) EnvironmentDetailModel? data = null; var requestUri = $"api/v1/env/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.EnvironmentService.GetAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -49,12 +49,12 @@ public async Task TestGetListAsync() }; var requestUri = $"api/v1/env"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.EnvironmentService.GetListAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -65,12 +65,12 @@ public async Task TestGetList1Async() List? data = null; var requestUri = $"api/v1/env"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.EnvironmentService.GetListAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 0); } diff --git a/test/Masa.Contrib.BasicAbility.Pm.Tests/ProjectServiceTest.cs b/test/Masa.Contrib.BasicAbility.Pm.Tests/ProjectServiceTest.cs index 04178f23e..2982e4786 100644 --- a/test/Masa.Contrib.BasicAbility.Pm.Tests/ProjectServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Pm.Tests/ProjectServiceTest.cs @@ -15,12 +15,12 @@ public async Task TestGetProjectAppsAsync() }; string env = "development"; var requestUri = $"api/v1/projectwithapps/{env}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ProjectService.GetProjectAppsAsync(env); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -30,13 +30,13 @@ public async Task TestGetProjectApps2Async() List? data = null; string env = "development"; var requestUri = $"api/v1/projectwithapps/{env}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => (provider.GetAsync>(It.IsAny(), default))).ReturnsAsync(data) + var caller = new Mock(); + caller.Setup(provider => (provider.GetAsync>(It.IsAny(), default))).ReturnsAsync(data) .Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ProjectService.GetProjectAppsAsync(env); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 0); } @@ -48,12 +48,12 @@ public async Task TestGetAsync(int Id) var data = new ProjectDetailModel(); var requestUri = $"api/v1/project/{Id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ProjectService.GetAsync(Id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -65,12 +65,12 @@ public async Task TestGet1Async(int id) ProjectDetailModel? data = null; var requestUri = $"api/v1/project/{id}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ProjectService.GetAsync(id); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -82,12 +82,12 @@ public async Task TestGetByIdentityAsync(string identity) var data = new ProjectDetailModel(); var requestUri = $"open-api/project/{identity}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ProjectService.GetByIdentityAsync(identity); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -99,12 +99,12 @@ public async Task TestGetByIdentity1Async(string identity) ProjectDetailModel? data = null; var requestUri = $"open-api/project/{identity}"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ProjectService.GetByIdentityAsync(identity); - callerProvider.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); Assert.IsNotNull(result); } @@ -118,12 +118,12 @@ public async Task TestGetListByEnvironmentClusterIdAsync(int envClusterId) new ProjectModel { Id = 1 } }; var requestUri = $"api/v1/{envClusterId}/project"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ProjectService.GetListByEnvironmentClusterIdAsync(envClusterId); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -134,12 +134,12 @@ public async Task TestGetListByEnvironmentClusterId1Async(int envClusterId) { List? data = null; var requestUri = $"api/v1/{envClusterId}/project"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ProjectService.GetListByEnvironmentClusterIdAsync(envClusterId); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 0); } @@ -153,12 +153,12 @@ public async Task TestGetListByTeamIdsAsync() }; var teamIds = new List { Guid.NewGuid() }; var requestUri = $"api/v1/project/teamProjects"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync>(requestUri, teamIds, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync>(requestUri, teamIds, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ProjectService.GetListByTeamIdsAsync(teamIds); - callerProvider.Verify(provider => provider.PostAsync>(requestUri, teamIds, default), Times.Once); + caller.Verify(provider => provider.PostAsync>(requestUri, teamIds, default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -169,12 +169,12 @@ public async Task TestGetListByTeamIds1Async() List? data = null; var teamIds = new List { Guid.NewGuid() }; var requestUri = $"api/v1/project/teamProjects"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.PostAsync>(It.IsAny(), It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.PostAsync>(It.IsAny(), It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ProjectService.GetListByTeamIdsAsync(teamIds); - callerProvider.Verify(provider => provider.PostAsync>(requestUri, teamIds, default), Times.Once); + caller.Verify(provider => provider.PostAsync>(requestUri, teamIds, default), Times.Once); Assert.IsTrue(result.Count == 0); } @@ -187,12 +187,12 @@ public async Task TestGetProjectTypesAsync() new ProjectTypeModel { Id = 1 } }; var requestUri = $"api/v1/project/projectType"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ProjectService.GetProjectTypesAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 1); } @@ -202,12 +202,12 @@ public async Task TestGetProjectTypes1Async() { List? data = null; var requestUri = $"api/v1/project/projectType"; - var callerProvider = new Mock(); - callerProvider.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(callerProvider.Object); + var caller = new Mock(); + caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); + var pmCaching = new PmClient(caller.Object); var result = await pmCaching.ProjectService.GetProjectTypesAsync(); - callerProvider.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); + caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); Assert.IsTrue(result.Count == 0); } diff --git a/test/Masa.Contrib.BasicAbility.Scheduler.Tests/SchedulerJobServiceTest.cs b/test/Masa.Contrib.BasicAbility.Scheduler.Tests/SchedulerJobServiceTest.cs index 59125c749..ac2c87c62 100644 --- a/test/Masa.Contrib.BasicAbility.Scheduler.Tests/SchedulerJobServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Scheduler.Tests/SchedulerJobServiceTest.cs @@ -45,12 +45,12 @@ public async Task TestAddSchedulerHttpJobAsync() }; var requestUri = $"{API}/addSchedulerJobBySdk"; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); var result = await schedulerClient.SchedulerJobService.AddAsync(requestData); - callerProvider.Verify(provider => provider.PostAsync(requestUri, requestData, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, requestData, default), Times.Once); Assert.AreNotEqual(Guid.Empty, result); } @@ -84,12 +84,12 @@ public async Task TestAddSchedulerJobApp() }; var requestUri = $"{API}/addSchedulerJobBySdk"; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); var result = await schedulerClient.SchedulerJobService.AddAsync(requestData); - callerProvider.Verify(provider => provider.PostAsync(requestUri, requestData, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, requestData, default), Times.Once); Assert.AreNotEqual(Guid.Empty, result); } @@ -122,12 +122,12 @@ public async Task TestAddSchedulerDaprServiceInvocationJob() }; var requestUri = $"{API}/addSchedulerJobBySdk"; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); var result = await schedulerClient.SchedulerJobService.AddAsync(requestData); - callerProvider.Verify(provider => provider.PostAsync(requestUri, requestData, default), Times.Once); + caller.Verify(provider => provider.PostAsync(requestUri, requestData, default), Times.Once); Assert.AreNotEqual(Guid.Empty, result); } @@ -160,10 +160,10 @@ public async Task TestAddSchedulerJobArgumentNullException() }; var requestUri = $"{API}/addSchedulerJobBySdk"; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); await Assert.ThrowsExceptionAsync(async () => await schedulerClient.SchedulerJobService.AddAsync(requestData)); } @@ -179,10 +179,10 @@ public async Task TestAddSchedulerHttpJobArgumentNullException() }; var requestUri = $"{API}/addSchedulerJobBySdk"; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); await Assert.ThrowsExceptionAsync(async () => await schedulerClient.SchedulerJobService.AddAsync(requestData)); } @@ -198,10 +198,10 @@ public async Task TestAddSchedulerJobAppArgumentNullException() }; var requestUri = $"{API}/addSchedulerJobBySdk"; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); await Assert.ThrowsExceptionAsync(async () => await schedulerClient.SchedulerJobService.AddAsync(requestData)); } @@ -217,10 +217,10 @@ public async Task TestAddSchedulerDaprInvocationJobArgumentNullException() }; var requestUri = $"{API}/addSchedulerJobBySdk"; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); await Assert.ThrowsExceptionAsync(async () => await schedulerClient.SchedulerJobService.AddAsync(requestData)); } @@ -233,12 +233,12 @@ public async Task TestRemoveSchedulerJobAsync() OperatorId = Guid.NewGuid() }; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.DeleteAsync(API, requestData, true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.DeleteAsync(API, requestData, true, default)).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); var result = await schedulerClient.SchedulerJobService.RemoveAsync(requestData); - callerProvider.Verify(provider => provider.DeleteAsync(API, requestData, true, default), Times.Once); + caller.Verify(provider => provider.DeleteAsync(API, requestData, true, default), Times.Once); Assert.IsTrue(result); } @@ -253,12 +253,12 @@ public async Task TestStartSchedulerJobAsync() }; var requestUri = $"{API}/startJob"; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.PutAsync(requestUri, requestData, true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.PutAsync(requestUri, requestData, true, default)).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); var result = await schedulerClient.SchedulerJobService.StartAsync(requestData); - callerProvider.Verify(provider => provider.PutAsync(requestUri, requestData, true, default), Times.Once); + caller.Verify(provider => provider.PutAsync(requestUri, requestData, true, default), Times.Once); Assert.IsTrue(result); } @@ -272,12 +272,12 @@ public async Task TestEnableSchedulerJob() }; var requestUri = $"{API}/changeEnableStatus"; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.PutAsync(requestUri, It.IsAny(), true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.PutAsync(requestUri, It.IsAny(), true, default)).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); var result = await schedulerClient.SchedulerJobService.EnableAsync(requestData); - callerProvider.Verify(provider => provider.PutAsync(requestUri, It.IsAny(), true, default), Times.Once); + caller.Verify(provider => provider.PutAsync(requestUri, It.IsAny(), true, default), Times.Once); Assert.IsTrue(result); } @@ -291,12 +291,12 @@ public async Task TestDisableSchedulerJob() }; var requestUri = $"{API}/changeEnableStatus"; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.PutAsync(requestUri, It.IsAny(), true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.PutAsync(requestUri, It.IsAny(), true, default)).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); var result = await schedulerClient.SchedulerJobService.DisableAsync(requestData); - callerProvider.Verify(provider => provider.PutAsync(requestUri, It.IsAny(), true, default), Times.Once); + caller.Verify(provider => provider.PutAsync(requestUri, It.IsAny(), true, default), Times.Once); Assert.IsTrue(result); } } diff --git a/test/Masa.Contrib.BasicAbility.Scheduler.Tests/SchedulerTaskServiceTest.cs b/test/Masa.Contrib.BasicAbility.Scheduler.Tests/SchedulerTaskServiceTest.cs index a18086153..558b6ba14 100644 --- a/test/Masa.Contrib.BasicAbility.Scheduler.Tests/SchedulerTaskServiceTest.cs +++ b/test/Masa.Contrib.BasicAbility.Scheduler.Tests/SchedulerTaskServiceTest.cs @@ -18,12 +18,12 @@ public async Task TestStopSchedulerTaskAsync() }; var requestUri = $"{API}/stop"; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.PutAsync(requestUri, requestData, true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.PutAsync(requestUri, requestData, true, default)).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); var result = await schedulerClient.SchedulerTaskService.StopAsync(requestData); - callerProvider.Verify(provider => provider.PutAsync(requestUri, requestData, true, default), Times.Once); + caller.Verify(provider => provider.PutAsync(requestUri, requestData, true, default), Times.Once); Assert.IsTrue(result); } @@ -37,12 +37,12 @@ public async Task TestStartSchedulerTaskAsync() }; var requestUri = $"{API}/start"; - var callerProvider = new Mock(); + var caller = new Mock(); var loggerFactory = new Mock(); - callerProvider.Setup(provider => provider.PutAsync(requestUri, It.IsAny(), true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(callerProvider.Object, loggerFactory.Object); + caller.Setup(provider => provider.PutAsync(requestUri, It.IsAny(), true, default)).Verifiable(); + var schedulerClient = new SchedulerClient(caller.Object, loggerFactory.Object); var result = await schedulerClient.SchedulerTaskService.StartAsync(request); - callerProvider.Verify(provider => provider.PutAsync(requestUri, It.IsAny(), true, default), Times.Once); + caller.Verify(provider => provider.PutAsync(requestUri, It.IsAny(), true, default), Times.Once); Assert.IsTrue(result); } } diff --git a/test/Masa.Contrib.BasicAbility.Tsc.Test/Extensions/CallerProviderExtensionsTests.cs b/test/Masa.Contrib.BasicAbility.Tsc.Test/Extensions/CallerProviderExtensionsTests.cs index 49564a7b3..a84ee144e 100644 --- a/test/Masa.Contrib.BasicAbility.Tsc.Test/Extensions/CallerProviderExtensionsTests.cs +++ b/test/Masa.Contrib.BasicAbility.Tsc.Test/Extensions/CallerProviderExtensionsTests.cs @@ -9,12 +9,12 @@ public class CallerProviderExtensionsTests [TestMethod] public async Task SendGetRequestWithBodyParameterAsyncTest() { - var callerProvider = new Mock(); + var caller = new Mock(); string url = "http://locahost:80/test"; var param = new { name = "name" }; var result = "ok"; - callerProvider.Setup(provider => provider.SendAsync(It.IsAny(), default)).ReturnsAsync(result); - var str = await callerProvider.Object.GetByBodyAsync(url, "name"); + caller.Setup(provider => provider.SendAsync(It.IsAny(), default)).ReturnsAsync(result); + var str = await caller.Object.GetByBodyAsync(url, "name"); Assert.IsNotNull(str); Assert.AreEqual(result, str); } diff --git a/test/Masa.Contrib.BasicAbility.Tsc.Test/Service/LogServiceTests.cs b/test/Masa.Contrib.BasicAbility.Tsc.Test/Service/LogServiceTests.cs index f21102398..7f4ebd859 100644 --- a/test/Masa.Contrib.BasicAbility.Tsc.Test/Service/LogServiceTests.cs +++ b/test/Masa.Contrib.BasicAbility.Tsc.Test/Service/LogServiceTests.cs @@ -9,7 +9,7 @@ public class LogServiceTests [TestMethod] public async Task GetMappingFieldsAsyncTest() { - var callerProvider = new Mock(); + var caller = new Mock(); var time = DateTime.Now; var query = new LableValuesRequest @@ -25,8 +25,8 @@ public async Task GetMappingFieldsAsyncTest() "container.instance.name", "Id" }; - callerProvider.Setup(provider => provider.GetAsync>(LogService.FIELD_URI, default)).ReturnsAsync(data).Verifiable(); - var client = new TscClient(callerProvider.Object); + caller.Setup(provider => provider.GetAsync>(LogService.FIELD_URI, default)).ReturnsAsync(data).Verifiable(); + var client = new TscClient(caller.Object); var result = await client.LogService.GetFieldsAsync(); Assert.IsNotNull(result); } @@ -34,7 +34,7 @@ public async Task GetMappingFieldsAsyncTest() [TestMethod] public async Task GetAggregationAsyncTest() { - var callerProvider = new Mock(); + var caller = new Mock(); var time = DateTime.Now; var query = new LogAggregationRequest @@ -60,8 +60,8 @@ public async Task GetAggregationAsyncTest() {"count1","0" }, { "count2","0"} }; - callerProvider.Setup(provider => provider.GetAsync>>(LogService.FIELD_URI, query, default)).ReturnsAsync(data).Verifiable(); - var client = new TscClient(callerProvider.Object); + caller.Setup(provider => provider.GetAsync>>(LogService.FIELD_URI, query, default)).ReturnsAsync(data).Verifiable(); + var client = new TscClient(caller.Object); var result = await client.LogService.GetAggregationAsync(query); Assert.IsNotNull(result); @@ -70,7 +70,7 @@ public async Task GetAggregationAsyncTest() [TestMethod] public async Task GetLatestAsyncTest() { - var callerProvider = new Mock(); + var caller = new Mock(); var time = DateTime.Now; var query = new LogLatestRequest @@ -88,8 +88,8 @@ public async Task GetLatestAsyncTest() }; options.Converters.Add(new JsonStringEnumConverter()); var data = JsonSerializer.Deserialize(str, options); - callerProvider.Setup(provider => provider.GetAsync(LogService.LATEST_URI, query, default)).ReturnsAsync(data).Verifiable(); - var client = new TscClient(callerProvider.Object); + caller.Setup(provider => provider.GetAsync(LogService.LATEST_URI, query, default)).ReturnsAsync(data).Verifiable(); + var client = new TscClient(caller.Object); var result = await client.LogService.GetLatestAsync(query); Assert.IsNotNull(result); diff --git a/test/Masa.Contrib.BasicAbility.Tsc.Test/Service/MetricServiceTests.cs b/test/Masa.Contrib.BasicAbility.Tsc.Test/Service/MetricServiceTests.cs index e9a227745..1b49815d4 100644 --- a/test/Masa.Contrib.BasicAbility.Tsc.Test/Service/MetricServiceTests.cs +++ b/test/Masa.Contrib.BasicAbility.Tsc.Test/Service/MetricServiceTests.cs @@ -13,7 +13,7 @@ public class MetricServiceTests public async Task GetNamesAsyncTest(IEnumerable match) { var data = new string[] { "up", "prometheus_http_requests_total", "prometheus_http_request_duration_seconds_count" }; - var caller = new Mock(); + var caller = new Mock(); caller.Setup(provider => provider.GetAsync?>(MetricService.NAMES_URI, It.Is>(dic => dic == null || dic.ContainsKey("match")), default)) .ReturnsAsync((string? url, Dictionary param, CancellationToken token) => { @@ -39,7 +39,7 @@ public async Task GetNamesAsyncTest(IEnumerable match) [DataRow("up", "2022-07-01T09:00:00.000Z", "2022-07-05T22:00:00.000Z")] public async Task GetLabelValuesAsyncTest(string match, string start, string end) { - var caller = new Mock(); + var caller = new Mock(); caller.Setup(provider => provider.SendAsync>>>(It.IsNotNull(), default)) .ReturnsAsync(new Dictionary>> { {"up",new Dictionary>{ @@ -65,7 +65,7 @@ public async Task GetLabelValuesAsyncTest(string match, string start, string end [DataRow("up", null, "2022-07-01T09:00:00.000Z", "2022-07-05T22:00:00.000Z")] public async Task GetValuesAsyncTest(string match, IEnumerable labels, string start, string end) { - var caller = new Mock(); + var caller = new Mock(); caller.Setup(provider => provider.SendAsync(It.IsNotNull(), default)).ReturnsAsync("1.0"); var client = new TscClient(caller.Object); diff --git a/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccManageTest.cs b/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccManageTest.cs index b5e979a00..115ccff3a 100644 --- a/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccManageTest.cs +++ b/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccManageTest.cs @@ -10,7 +10,7 @@ public class DccManageTest { private DccSectionOptions _dccSectionOptions; private JsonSerializerOptions _jsonSerializerOptions; - private Mock _callerProvider; + private Mock _caller; [TestInitialize] public void Initialize() @@ -30,7 +30,7 @@ public void Initialize() { PropertyNameCaseInsensitive = true }; - _callerProvider = new Mock(); + _caller = new Mock(); } [DataTestMethod] @@ -38,13 +38,13 @@ public void Initialize() public async Task TestUpdateAsync(string environment, string cluster, string appId, string configObject) { var brand = new Brands("Microsoft"); - _callerProvider.Setup(factory => factory.PutAsync(It.IsAny(), It.IsAny(), false, default).Result).Returns(() => new HttpResponseMessage() + _caller.Setup(factory => factory.PutAsync(It.IsAny(), It.IsAny(), false, default).Result).Returns(() => new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(brand.Serialize(_jsonSerializerOptions)) }).Verifiable(); - var manage = new ConfigurationApiManage(_callerProvider.Object, _dccSectionOptions, null); + var manage = new ConfigurationApiManage(_caller.Object, _dccSectionOptions, null); await manage.UpdateAsync(environment, cluster, appId, configObject, brand); } @@ -54,13 +54,13 @@ public async Task TestUpdateAsyncAndError(string environment, string cluster, st { var brand = new Brands("Microsoft"); - _callerProvider.Setup(factory => factory.PutAsync(It.IsAny(), It.IsAny(), false, default).Result).Returns(() => new HttpResponseMessage() + _caller.Setup(factory => factory.PutAsync(It.IsAny(), It.IsAny(), false, default).Result).Returns(() => new HttpResponseMessage() { StatusCode = HttpStatusCode.ExpectationFailed, Content = new StringContent("error") }).Verifiable(); - var manage = new ConfigurationApiManage(_callerProvider.Object, _dccSectionOptions, null); + var manage = new ConfigurationApiManage(_caller.Object, _dccSectionOptions, null); await Assert.ThrowsExceptionAsync(async () => await manage.UpdateAsync(environment, cluster, appId, configObject, brand)); } @@ -69,13 +69,13 @@ public async Task TestUpdateAsyncAndError(string environment, string cluster, st public async Task TestUpdateAsyncAndCustomError(string environment, string cluster, string appId, string configObject) { var brand = new Brands("Microsoft"); - _callerProvider.Setup(factory => factory.PutAsync(It.IsAny(), It.IsAny(), false, default).Result).Returns(() => new HttpResponseMessage() + _caller.Setup(factory => factory.PutAsync(It.IsAny(), It.IsAny(), false, default).Result).Returns(() => new HttpResponseMessage() { StatusCode = (HttpStatusCode)299, Content = new StringContent("custom error") }).Verifiable(); - var manage = new ConfigurationApiManage(_callerProvider.Object, _dccSectionOptions, null); + var manage = new ConfigurationApiManage(_caller.Object, _dccSectionOptions, null); await Assert.ThrowsExceptionAsync(async () => await manage.UpdateAsync(environment, cluster, appId, configObject, brand)); } @@ -87,13 +87,13 @@ public async Task TestInitAsync(string environment, string cluster, string appId { { "Appsettings", "{\"ConnectionStrings\":\"xxxx\"}" } }; - _callerProvider.Setup(factory => factory.PostAsync(It.IsAny(), It.IsAny(), false, default).Result).Returns(() => new HttpResponseMessage() + _caller.Setup(factory => factory.PostAsync(It.IsAny(), It.IsAny(), false, default).Result).Returns(() => new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(configObjects.Serialize(_jsonSerializerOptions)) }).Verifiable(); - var manage = new ConfigurationApiManage(_callerProvider.Object, _dccSectionOptions, null); + var manage = new ConfigurationApiManage(_caller.Object, _dccSectionOptions, null); await manage.InitializeAsync(environment, cluster, appId, configObjects); } @@ -106,13 +106,13 @@ public async Task TestInitAsyncAndError(string environment, string cluster, stri { "Appsettings", "{\"ConnectionStrings\":\"xxxx\"}" } }; - _callerProvider.Setup(factory => factory.PostAsync(It.IsAny(), It.IsAny(), false, default).Result).Returns(() => new HttpResponseMessage() + _caller.Setup(factory => factory.PostAsync(It.IsAny(), It.IsAny(), false, default).Result).Returns(() => new HttpResponseMessage() { StatusCode = HttpStatusCode.ExpectationFailed, Content = new StringContent("error") }).Verifiable(); - var manage = new ConfigurationApiManage(_callerProvider.Object, _dccSectionOptions, null); + var manage = new ConfigurationApiManage(_caller.Object, _dccSectionOptions, null); await Assert.ThrowsExceptionAsync(async () => await manage.InitializeAsync(environment, cluster, appId, configObjects)); } @@ -125,13 +125,13 @@ public async Task TestInitAsyncAndCustomError(string environment, string cluster { "Appsettings", "{\"ConnectionStrings\":\"xxxx\"}" } }; - _callerProvider.Setup(factory => factory.PostAsync(It.IsAny(), It.IsAny(), false, default).Result).Returns(() => new HttpResponseMessage() + _caller.Setup(factory => factory.PostAsync(It.IsAny(), It.IsAny(), false, default).Result).Returns(() => new HttpResponseMessage() { StatusCode = (HttpStatusCode)299, Content = new StringContent("custom error") }).Verifiable(); - var manage = new ConfigurationApiManage(_callerProvider.Object, _dccSectionOptions, null); + var manage = new ConfigurationApiManage(_caller.Object, _dccSectionOptions, null); await Assert.ThrowsExceptionAsync(async () => await manage.InitializeAsync(environment, cluster, appId, configObjects)); } diff --git a/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccTest.cs b/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccTest.cs index 73771f25a..bed38fa52 100644 --- a/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccTest.cs +++ b/test/Masa.Contrib.Configuration.ConfigurationApi.Dcc.Tests/DccTest.cs @@ -161,8 +161,8 @@ public void TestCustomCaller() builder.Configure = opt => opt.BaseAddress = new Uri("https://github.com"); }); }); - var callerProvider = _services.BuildServiceProvider().GetRequiredService().CreateClient("CustomHttpClient"); - Assert.IsNotNull(callerProvider); + var caller = _services.BuildServiceProvider().GetRequiredService().Create("CustomHttpClient"); + Assert.IsNotNull(caller); } [TestMethod] diff --git a/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/CustomizeDbContext.cs b/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/CustomDbContext.cs similarity index 74% rename from test/Masa.Contrib.Data.EntityFrameworkCore.Tests/CustomizeDbContext.cs rename to test/Masa.Contrib.Data.EntityFrameworkCore.Tests/CustomDbContext.cs index 5f8997920..9538e0227 100644 --- a/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/CustomizeDbContext.cs +++ b/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/CustomDbContext.cs @@ -3,9 +3,9 @@ namespace Masa.Contrib.Data.EntityFrameworkCore.Tests; -public class CustomizeDbContext : MasaDbContext +public class CustomDbContext : MasaDbContext { - public CustomizeDbContext(MasaDbContextOptions options) : base(options) + public CustomDbContext(MasaDbContextOptions options) : base(options) { } diff --git a/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/DbContextTest.cs b/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/DbContextTest.cs index f531ac62d..e72d3336d 100644 --- a/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/DbContextTest.cs +++ b/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/DbContextTest.cs @@ -105,10 +105,10 @@ public async Task TestSoftDeleteAsync() [TestMethod] public async Task TestDisabledSoftDelete() { - Services.AddMasaDbContext(options + Services.AddMasaDbContext(options => options.UseTestFilter().UseTestSqlite($"data source=disabled-soft-delete-db-{Guid.NewGuid()}")); var serviceProvider = Services.BuildServiceProvider(); - var dbContext = serviceProvider.GetRequiredService(); + var dbContext = serviceProvider.GetRequiredService(); await dbContext.Database.EnsureCreatedAsync(); var student = new Student { @@ -142,8 +142,8 @@ public async Task TestDisabledSoftDelete() public void TestAddMultiMasaDbContextReturnSaveChangeFilterEqual1() { var services = new ServiceCollection(); - services.AddMasaDbContext() - .AddMasaDbContext(); + services.AddMasaDbContext() + .AddMasaDbContext(); var serviceProvider = services.BuildServiceProvider(); Assert.IsTrue(serviceProvider.GetServices().Count() == 1); @@ -153,7 +153,7 @@ public void TestAddMultiMasaDbContextReturnSaveChangeFilterEqual1() public void TestAddMasaDbContextReturnSaveChangeFilterEqual2() { var services = new ServiceCollection(); - services.AddMasaDbContext(opt => + services.AddMasaDbContext(opt => { opt.UseTestSqlite(Guid.NewGuid().ToString()).UseFilter(); }); diff --git a/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/Internal/Repository.cs b/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/Internal/Repository.cs index 82bde9172..8977dee53 100644 --- a/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/Internal/Repository.cs +++ b/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/Internal/Repository.cs @@ -5,9 +5,9 @@ namespace Masa.Contrib.Data.EntityFrameworkCore.Tests.Internal; internal class Repository { - private readonly CustomizeDbContext _testDbContext; + private readonly CustomDbContext _testDbContext; - public Repository(CustomizeDbContext testDbContext) => _testDbContext = testDbContext; + public Repository(CustomDbContext testDbContext) => _testDbContext = testDbContext; public Task> GetPaginatedListAsync(int skip, int take, CancellationToken cancellationToken = default) => _testDbContext.Set().Skip(skip).Take(take).ToListAsync(cancellationToken); diff --git a/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/TestBase.cs b/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/TestBase.cs index d25be19df..1f6585563 100644 --- a/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/TestBase.cs +++ b/test/Masa.Contrib.Data.EntityFrameworkCore.Tests/TestBase.cs @@ -13,10 +13,10 @@ public void Initialize() Services = new ServiceCollection(); } - protected CustomizeDbContext CreateDbContext(bool enableSoftDelete, out IServiceProvider serviceProvider, + protected CustomDbContext CreateDbContext(bool enableSoftDelete, out IServiceProvider serviceProvider, bool initConnectionString = true) { - Services.AddMasaDbContext(options => + Services.AddMasaDbContext(options => { if (enableSoftDelete) options.UseTestFilter(); @@ -27,7 +27,7 @@ protected CustomizeDbContext CreateDbContext(bool enableSoftDelete, out IService options.UseSqlite(); }); serviceProvider = Services.BuildServiceProvider(); - var dbContext = serviceProvider.GetRequiredService(); + var dbContext = serviceProvider.GetRequiredService(); dbContext.Database.EnsureCreated(); return dbContext; } diff --git a/test/Masa.Contrib.Data.IdGenerator.Snowflake.Tests/CustomizeDistributedWorkerProvider.cs b/test/Masa.Contrib.Data.IdGenerator.Snowflake.Tests/CustomDistributedWorkerProvider.cs similarity index 78% rename from test/Masa.Contrib.Data.IdGenerator.Snowflake.Tests/CustomizeDistributedWorkerProvider.cs rename to test/Masa.Contrib.Data.IdGenerator.Snowflake.Tests/CustomDistributedWorkerProvider.cs index 556e83e16..316f17bcc 100644 --- a/test/Masa.Contrib.Data.IdGenerator.Snowflake.Tests/CustomizeDistributedWorkerProvider.cs +++ b/test/Masa.Contrib.Data.IdGenerator.Snowflake.Tests/CustomDistributedWorkerProvider.cs @@ -3,9 +3,9 @@ namespace Masa.Contrib.Data.IdGenerator.Snowflake.Tests; -public class CustomizeDistributedWorkerProvider : DistributedWorkerProvider +public class CustomDistributedWorkerProvider : DistributedWorkerProvider { - public CustomizeDistributedWorkerProvider(IDistributedCacheClient distributedCacheClient, + public CustomDistributedWorkerProvider(IDistributedCacheClient distributedCacheClient, DistributedIdGeneratorOptions? distributedIdGeneratorOptions, IOptions redisOptions, ILogger? logger) diff --git a/test/Masa.Contrib.Data.IdGenerator.Snowflake.Tests/IdGeneratorTest.cs b/test/Masa.Contrib.Data.IdGenerator.Snowflake.Tests/IdGeneratorTest.cs index 89992c2b8..42def1c0a 100644 --- a/test/Masa.Contrib.Data.IdGenerator.Snowflake.Tests/IdGeneratorTest.cs +++ b/test/Masa.Contrib.Data.IdGenerator.Snowflake.Tests/IdGeneratorTest.cs @@ -324,7 +324,7 @@ private IWorkerProvider GetWorkerProvider(IServiceCollection? services, int work { GetWorkerIdMinInterval = 0 }; - return new CustomizeDistributedWorkerProvider(_redisCacheClient, distributedIdGeneratorOptions, _redisOptions, null); + return new CustomDistributedWorkerProvider(_redisCacheClient, distributedIdGeneratorOptions, _redisOptions, null); } private ConfigurationOptions GetConfigurationOptions(RedisConfigurationOptions redisOptions) diff --git a/test/Masa.Contrib.Ddd.Domain.Integrated.Tests/CustomizeDbContext.cs b/test/Masa.Contrib.Ddd.Domain.Integrated.Tests/CustomDbContext.cs similarity index 61% rename from test/Masa.Contrib.Ddd.Domain.Integrated.Tests/CustomizeDbContext.cs rename to test/Masa.Contrib.Ddd.Domain.Integrated.Tests/CustomDbContext.cs index 677452c3d..8272e9dc7 100644 --- a/test/Masa.Contrib.Ddd.Domain.Integrated.Tests/CustomizeDbContext.cs +++ b/test/Masa.Contrib.Ddd.Domain.Integrated.Tests/CustomDbContext.cs @@ -3,11 +3,11 @@ namespace Masa.Contrib.Ddd.Domain.Integrated.Tests; -public class CustomizeDbContext : MasaDbContext +public class CustomDbContext : MasaDbContext { public DbSet User { get; set; } - public CustomizeDbContext(MasaDbContextOptions options) : base(options) + public CustomDbContext(MasaDbContextOptions options) : base(options) { } } diff --git a/test/Masa.Contrib.Ddd.Domain.Integrated.Tests/DomainEventTest.cs b/test/Masa.Contrib.Ddd.Domain.Integrated.Tests/DomainEventTest.cs index 5f80aae57..f59257e89 100644 --- a/test/Masa.Contrib.Ddd.Domain.Integrated.Tests/DomainEventTest.cs +++ b/test/Masa.Contrib.Ddd.Domain.Integrated.Tests/DomainEventTest.cs @@ -25,11 +25,11 @@ public void Initialize() .UseIntegrationEventBus(options => { options.UseDapr(); - options.UseEventLog(); + options.UseEventLog(); }) .UseEventBus() - .UseUoW(dbOptions => dbOptions.UseSqlite()) - .UseRepository(); + .UseUoW(dbOptions => dbOptions.UseSqlite()) + .UseRepository(); }); _serviceProvider = services.BuildServiceProvider(); } @@ -44,14 +44,14 @@ public async Task TestInsertAsyncReturnUserNameEqualTom() .UseIntegrationEventBus(options => { options.UseDapr(); - options.UseEventLog(); + options.UseEventLog(); }) .UseEventBus() - .UseUoW(dbOptions => dbOptions.UseTestSqlite($"data source=test-{Guid.NewGuid()}")) - .UseRepository(); + .UseUoW(dbOptions => dbOptions.UseTestSqlite($"data source=test-{Guid.NewGuid()}")) + .UseRepository(); }); var serviceProvider = services.BuildServiceProvider(); - var dbContext = serviceProvider.GetRequiredService(); + var dbContext = serviceProvider.GetRequiredService(); await dbContext.Database.EnsureCreatedAsync(); var eventBus = serviceProvider.GetRequiredService(); var @event = new RegisterUserEvent() @@ -69,7 +69,7 @@ public async Task TestInsertAsyncReturnUserNameEqualTom() [TestMethod] public async Task TestPublishMultiCommandReturnDataIs2() { - var dbContext = _serviceProvider.GetRequiredService(); + var dbContext = _serviceProvider.GetRequiredService(); await dbContext.Database.EnsureCreatedAsync(); var eventBus = _serviceProvider.GetRequiredService(); @@ -95,7 +95,7 @@ public async Task TestPublishMultiCommandReturnDataIs2() [TestMethod] public async Task TestPublishMultiCommandReturnDataIs1() { - var dbContext = _serviceProvider.GetRequiredService(); + var dbContext = _serviceProvider.GetRequiredService(); await dbContext.Database.EnsureCreatedAsync(); var eventBus = _serviceProvider.GetRequiredService(); diff --git a/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/Domain/Repositories/IOrderRepository.cs b/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/Domain/Repositories/IOrderRepository.cs index 78f739535..070c1a005 100644 --- a/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/Domain/Repositories/IOrderRepository.cs +++ b/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/Domain/Repositories/IOrderRepository.cs @@ -8,7 +8,7 @@ public interface IOrderRepository : IRepository Task AddAsync(Orders order); } -public interface ICustomizeOrderRepository : IRepository +public interface ICustomOrderRepository : IRepository { } diff --git a/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/Infrastructure/Repositories/OrderRepository.cs b/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/Infrastructure/Repositories/OrderRepository.cs index 05e039197..88a79437d 100644 --- a/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/Infrastructure/Repositories/OrderRepository.cs +++ b/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/Infrastructure/Repositories/OrderRepository.cs @@ -28,9 +28,9 @@ public async Task AddAsync(Orders order) } } -public class CustomizeOrderRepository : Repository, ICustomizeOrderRepository +public class CustomOrderRepository : Repository, ICustomOrderRepository { - public CustomizeOrderRepository(CustomDbContext context, IUnitOfWork unitOfWork) : base(context, unitOfWork) + public CustomOrderRepository(CustomDbContext context, IUnitOfWork unitOfWork) : base(context, unitOfWork) { } } diff --git a/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/RepositoryTest.cs b/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/RepositoryTest.cs index 51a109d09..74f5ea469 100644 --- a/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/RepositoryTest.cs +++ b/test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/RepositoryTest.cs @@ -150,7 +150,7 @@ public async Task TestGetPaginatedListAsync() { _dispatcherOptions.Object.UseRepository(); var serviceProvider = _services.BuildServiceProvider(); - var customizeOrderRepository = serviceProvider.GetRequiredService(); + var customOrderRepository = serviceProvider.GetRequiredService(); var orders = new List { @@ -170,8 +170,8 @@ public async Task TestGetPaginatedListAsync() OrderNumber = 20220227 } }; - await customizeOrderRepository.AddRangeAsync(orders); - await customizeOrderRepository.UnitOfWork.SaveChangesAsync(); + await customOrderRepository.AddRangeAsync(orders); + await customOrderRepository.UnitOfWork.SaveChangesAsync(); var sorting = new Dictionary( new List> @@ -179,7 +179,7 @@ public async Task TestGetPaginatedListAsync() new("OrderNumber", true), new("Description", false) }); - var list = await customizeOrderRepository.GetPaginatedListAsync( + var list = await customOrderRepository.GetPaginatedListAsync( 0, 10, sorting); @@ -193,7 +193,7 @@ public async Task TestGetPaginatedListAsync() new("OrderNumber", false), new("Description", true) }); - list = await customizeOrderRepository.GetPaginatedListAsync( + list = await customOrderRepository.GetPaginatedListAsync( order => order.Id != 3, 0, 10, @@ -201,14 +201,14 @@ public async Task TestGetPaginatedListAsync() Assert.IsTrue(list[0].Id == 2); Assert.IsTrue(list[1].Id == 1); - list = await customizeOrderRepository.GetPaginatedListAsync( + list = await customOrderRepository.GetPaginatedListAsync( order => order.Id != 3, 0, 10); Assert.IsTrue(list[0].Id == 1); //If you do not specify a sort value, the database will sort by default Assert.IsTrue(list[1].Id == 2); - list = await customizeOrderRepository.GetPaginatedListAsync(0, 10); + list = await customOrderRepository.GetPaginatedListAsync(0, 10); Assert.IsTrue(list[0].Id == 1); //If you do not specify a sort value, the database will sort by default Assert.IsTrue(list[1].Id == 2); } @@ -307,13 +307,13 @@ public async Task TestFindAsync() } [TestMethod] - public void TestCustomizeOrderRepository() + public void TestCustomOrderRepository() { _dispatcherOptions.Object.UseRepository(); var serviceProvider = _services.BuildServiceProvider(); - var customizeOrderRepository = serviceProvider.GetService(); - Assert.IsNotNull(customizeOrderRepository); + var customOrderRepository = serviceProvider.GetService(); + Assert.IsNotNull(customOrderRepository); } [TestMethod] diff --git a/test/Masa.Contrib.Ddd.Domain.Tests/DomainEventBusTest.cs b/test/Masa.Contrib.Ddd.Domain.Tests/DomainEventBusTest.cs index 380eff273..8b92262c7 100644 --- a/test/Masa.Contrib.Ddd.Domain.Tests/DomainEventBusTest.cs +++ b/test/Masa.Contrib.Ddd.Domain.Tests/DomainEventBusTest.cs @@ -265,19 +265,19 @@ public void TestParameterInitialization() var id = Guid.NewGuid(); var createTime = DateTime.UtcNow; - var domainCommand = new CustomizeDomainCommand(); + var domainCommand = new CustomDomainCommand(); Assert.IsTrue(domainCommand.GetEventId() != default); Assert.IsTrue(domainCommand.GetCreationTime() != default && domainCommand.GetCreationTime() >= createTime); - domainCommand = new CustomizeDomainCommand(id, createTime); + domainCommand = new CustomDomainCommand(id, createTime); Assert.IsTrue(domainCommand.GetEventId() == id); Assert.IsTrue(domainCommand.GetCreationTime() == createTime); - var domainEvent = new CustomizeDomainEvent(); + var domainEvent = new CustomDomainEvent(); Assert.IsTrue(domainEvent.GetEventId() != default); Assert.IsTrue(domainEvent.GetCreationTime() != default && domainEvent.GetCreationTime() >= createTime); - domainEvent = new CustomizeDomainEvent(id, createTime); + domainEvent = new CustomDomainEvent(id, createTime); Assert.IsTrue(domainEvent.GetEventId() == id); Assert.IsTrue(domainEvent.GetCreationTime() == createTime); diff --git a/test/Masa.Contrib.Ddd.Domain.Tests/Events/CustomizeDomainEvent.cs b/test/Masa.Contrib.Ddd.Domain.Tests/Events/CustomDomainCommand.cs similarity index 54% rename from test/Masa.Contrib.Ddd.Domain.Tests/Events/CustomizeDomainEvent.cs rename to test/Masa.Contrib.Ddd.Domain.Tests/Events/CustomDomainCommand.cs index b9422a495..6c6528998 100644 --- a/test/Masa.Contrib.Ddd.Domain.Tests/Events/CustomizeDomainEvent.cs +++ b/test/Masa.Contrib.Ddd.Domain.Tests/Events/CustomDomainCommand.cs @@ -3,14 +3,14 @@ namespace Masa.Contrib.Ddd.Domain.Tests.Events; -public record CustomizeDomainEvent : DomainEvent +public record CustomDomainCommand : DomainCommand { - public CustomizeDomainEvent() : base() + public CustomDomainCommand() : base() { } - public CustomizeDomainEvent(Guid eventId, DateTime creationTime) : base(eventId, creationTime) + public CustomDomainCommand(Guid eventId, DateTime creationTime) : base(eventId, creationTime) { } } diff --git a/test/Masa.Contrib.Ddd.Domain.Tests/Events/CustomizeDomainCommand.cs b/test/Masa.Contrib.Ddd.Domain.Tests/Events/CustomDomainEvent.cs similarity index 53% rename from test/Masa.Contrib.Ddd.Domain.Tests/Events/CustomizeDomainCommand.cs rename to test/Masa.Contrib.Ddd.Domain.Tests/Events/CustomDomainEvent.cs index 745d84cbb..21581a308 100644 --- a/test/Masa.Contrib.Ddd.Domain.Tests/Events/CustomizeDomainCommand.cs +++ b/test/Masa.Contrib.Ddd.Domain.Tests/Events/CustomDomainEvent.cs @@ -3,14 +3,14 @@ namespace Masa.Contrib.Ddd.Domain.Tests.Events; -public record CustomizeDomainCommand : DomainCommand +public record CustomDomainEvent : DomainEvent { - public CustomizeDomainCommand() : base() + public CustomDomainEvent() : base() { } - public CustomizeDomainCommand(Guid eventId, DateTime creationTime) : base(eventId, creationTime) + public CustomDomainEvent(Guid eventId, DateTime creationTime) : base(eventId, creationTime) { } } diff --git a/test/Masa.Contrib.Dispatcher.Events.Tests/CustomDbContext.cs b/test/Masa.Contrib.Dispatcher.Events.Tests/CustomDbContext.cs index 1abac8866..e320f72cc 100644 --- a/test/Masa.Contrib.Dispatcher.Events.Tests/CustomDbContext.cs +++ b/test/Masa.Contrib.Dispatcher.Events.Tests/CustomDbContext.cs @@ -3,7 +3,7 @@ namespace Masa.Contrib.Dispatcher.Events.Tests; -public class CustomizeDbContext : MasaDbContext +public class CustomDbContext : MasaDbContext { - public CustomizeDbContext(MasaDbContextOptions options) : base(options) { } + public CustomDbContext(MasaDbContextOptions options) : base(options) { } } diff --git a/test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs b/test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs index e5c1fc947..33000a439 100644 --- a/test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs +++ b/test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs @@ -387,14 +387,14 @@ public async Task TestEventBusFailedReturnExceptionIsUserFriendException() ServiceLifetime.Scoped, builder => { - builder.UseUoW(optionBuilder => + builder.UseUoW(optionBuilder => { optionBuilder.UseTestSqlite($"data source=test-{Guid.NewGuid()}"); }); }); var serviceProvider = services.BuildServiceProvider(); - var dbContext = serviceProvider.GetRequiredService(); + var dbContext = serviceProvider.GetRequiredService(); await dbContext.Database.EnsureCreatedAsync(); var eventBus = serviceProvider.GetRequiredService(); await Assert.ThrowsExceptionAsync(async () => await eventBus.PublishAsync(new SendCouponEvent())); diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/DispatcherOptionTest.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/DispatcherOptionTest.cs index 4d1f3bc5e..3fd775ccc 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/DispatcherOptionTest.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/DispatcherOptionTest.cs @@ -37,7 +37,7 @@ public void UseDaprEventBus() Mock distributedDispatcherOptions = new(); distributedDispatcherOptions.Setup(option => option.Services).Returns(services).Verifiable(); distributedDispatcherOptions.Setup(option => option.Assemblies).Returns(assemblies).Verifiable(); - distributedDispatcherOptions.Object.UseDaprEventBus("pubsub2"); + distributedDispatcherOptions.Object.UseDaprEventBus("pubsub2"); var serviceProvider = services.BuildServiceProvider(); var integrationEventBus = serviceProvider.GetService(); diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/IntegrationEventBusTest.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/IntegrationEventBusTest.cs index da06b59ba..71376914e 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/IntegrationEventBusTest.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/IntegrationEventBusTest.cs @@ -66,8 +66,8 @@ public void TestAddMultDaprEventBus() distributedDispatcherOptions.Setup(option => option.Services).Returns(services).Verifiable(); distributedDispatcherOptions.Setup(option => option.Assemblies).Returns(AppDomain.CurrentDomain.GetAssemblies()).Verifiable(); distributedDispatcherOptions.Object - .UseDaprEventBus() - .UseDaprEventBus(); + .UseDaprEventBus() + .UseDaprEventBus(); var serviceProvider = services.BuildServiceProvider(); Assert.IsTrue(serviceProvider.GetServices().Count() == 1); } @@ -76,7 +76,7 @@ public void TestAddMultDaprEventBus() public void TestAddDaprEventBus() { IServiceCollection services = new ServiceCollection(); - services.AddDaprEventBus(); + services.AddDaprEventBus(); var serviceProvider = services.BuildServiceProvider(); var integrationEventBus = serviceProvider.GetRequiredService(); Assert.IsNotNull(integrationEventBus); @@ -89,7 +89,7 @@ public void TestNotUseLoggerAndUoW() services.AddLogging(); services .AddDaprEventBus< - CustomizeIntegrationEventLogService>(); //The logger cannot be mocked and cannot verify that the logger is executed only once + CustomIntegrationEventLogService>(); //The logger cannot be mocked and cannot verify that the logger is executed only once var serviceProvider = services.BuildServiceProvider(); var integrationEventBus = serviceProvider.GetRequiredService(); @@ -101,7 +101,7 @@ public void TestUseLogger() { IServiceCollection services = new ServiceCollection(); - services.AddDaprEventBus(AppDomain.CurrentDomain.GetAssemblies(), option => + services.AddDaprEventBus(AppDomain.CurrentDomain.GetAssemblies(), option => { option.PubSubName = "pubsub"; }); @@ -118,7 +118,7 @@ public void TestAddDaprEventBusAndNullServicesAsync() distributedDispatcherOptions.Setup(option => option.Services).Returns(services).Verifiable(); distributedDispatcherOptions.Setup(option => option.Assemblies).Returns(AppDomain.CurrentDomain.GetAssemblies()).Verifiable(); Assert.ThrowsException(() => - distributedDispatcherOptions.Object.UseDaprEventBus(), + distributedDispatcherOptions.Object.UseDaprEventBus(), $"Value cannot be null. (Parameter '{nameof(_options.Object.Services)}')"); } @@ -126,7 +126,7 @@ public void TestAddDaprEventBusAndNullServicesAsync() public void TestUseDaprReturnNotNull() { var services = new ServiceCollection(); - services.AddIntegrationEventBus(opt => + services.AddIntegrationEventBus(opt => { opt.UseDapr(); }); diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/ProcessorTest.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/ProcessorTest.cs index c22c3c4e3..6a3920cf1 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/ProcessorTest.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr.Tests/ProcessorTest.cs @@ -13,7 +13,7 @@ public class ProcessorTest public void Initialize() { var services = new ServiceCollection(); - services.AddDaprEventBus(); + services.AddDaprEventBus(); _serviceProvider = services.BuildServiceProvider(); _options = Microsoft.Extensions.Options.Options.Create(new DispatcherOptions(services, AppDomain.CurrentDomain.GetAssemblies())); } @@ -83,8 +83,8 @@ public async Task DefaultHostedServiceTestAsync() var services = new ServiceCollection(); Mock unitOfWorkManager = new(); services.AddSingleton(_ => unitOfWorkManager.Object); - services.AddScoped(); - services.AddDaprEventBus(opt => + services.AddScoped(); + services.AddDaprEventBus(opt => { opt.CleaningLocalQueueExpireInterval = 1; opt.CleaningExpireInterval = 1; @@ -98,7 +98,7 @@ public async Task DefaultHostedServiceTestAsync() cancellationTokenSource.CancelAfter(5000); await hostedService.ExecuteAsync(cancellationTokenSource.Token); - Assert.IsTrue(CustomizeProcessor.Times > 0); + Assert.IsTrue(CustomProcessor.Times > 0); } [TestMethod] @@ -108,8 +108,8 @@ public async Task DefaultHostedServiceAndUseLoggerTestAsync() Mock unitOfWorkManager = new(); services.AddSingleton(_ => unitOfWorkManager.Object); services.AddLogging(); - services.AddScoped(); - services.AddDaprEventBus(opt => + services.AddScoped(); + services.AddDaprEventBus(opt => { opt.CleaningLocalQueueExpireInterval = 1; opt.CleaningExpireInterval = 1; @@ -123,6 +123,6 @@ public async Task DefaultHostedServiceAndUseLoggerTestAsync() cancellationTokenSource.CancelAfter(5000); await hostedService.ExecuteAsync(cancellationTokenSource.Token); - Assert.IsTrue(CustomizeProcessor.Times > 0); + Assert.IsTrue(CustomProcessor.Times > 0); } } diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/BackgroundServiceTest.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/BackgroundServiceTest.cs index f7b393ffe..99bb21525 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/BackgroundServiceTest.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/BackgroundServiceTest.cs @@ -1,8 +1,6 @@ // Copyright (c) MASA Stack All rights reserved. // Licensed under the MIT License. See LICENSE.txt in the project root for license information. -using Masa.Contrib.Dispatcher.IntegrationEvents.Tests.Infrastructure; - namespace Masa.Contrib.Dispatcher.IntegrationEvents.Tests; [TestClass] @@ -19,7 +17,7 @@ public async Task IntegrationEventHostedServiceTask() Mock processingServer = new(); processingServer.Setup(service => service.ExecuteAsync(default)).Verifiable(); - var integrationEventHostedService = new CustomizeIntegrationEventHostedService(processingServer.Object); + var integrationEventHostedService = new CustomIntegrationEventHostedService(processingServer.Object); await integrationEventHostedService.TestExecuteAsync(default); processingServer.Verify(service => service.ExecuteAsync(default), Times.Once); @@ -31,7 +29,7 @@ public async Task IntegrationEventHostedServiceAndUseLoggerTask() Mock processingServer = new(); processingServer.Setup(service => service.ExecuteAsync(default)).Verifiable(); - var integrationEventHostedService = new CustomizeIntegrationEventHostedService(processingServer.Object, new NullLoggerFactory()); + var integrationEventHostedService = new CustomIntegrationEventHostedService(processingServer.Object, new NullLoggerFactory()); await integrationEventHostedService.TestExecuteAsync(default); processingServer.Verify(service => service.ExecuteAsync(default), Times.Once); diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomizeIntegrationEventHostedService.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomIntegrationEventHostedService.cs similarity index 80% rename from test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomizeIntegrationEventHostedService.cs rename to test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomIntegrationEventHostedService.cs index 29da8664c..9fa0c9967 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomizeIntegrationEventHostedService.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomIntegrationEventHostedService.cs @@ -3,9 +3,9 @@ namespace Masa.Contrib.Dispatcher.IntegrationEvents.Tests.Infrastructure; -public class CustomizeIntegrationEventHostedService : IntegrationEventHostedService +public class CustomIntegrationEventHostedService : IntegrationEventHostedService { - public CustomizeIntegrationEventHostedService( + public CustomIntegrationEventHostedService( IProcessingServer processingServer, ILoggerFactory? loggerFactory = null) : base(processingServer, loggerFactory?.CreateLogger()) { diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomizeIntegrationEventLogService.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomIntegrationEventLogService.cs similarity index 93% rename from test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomizeIntegrationEventLogService.cs rename to test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomIntegrationEventLogService.cs index 3675e0831..2403d0ee1 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomizeIntegrationEventLogService.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomIntegrationEventLogService.cs @@ -3,7 +3,7 @@ namespace Masa.Contrib.Dispatcher.IntegrationEvents.Tests.Infrastructure; -public class CustomizeIntegrationEventLogService : IIntegrationEventLogService +public class CustomIntegrationEventLogService : IIntegrationEventLogService { public Task MarkEventAsFailedAsync(Guid eventId) { diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomizeProcessor.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomProcessor.cs similarity index 76% rename from test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomizeProcessor.cs rename to test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomProcessor.cs index 32031d4bc..1e8129489 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomizeProcessor.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/Infrastructure/CustomProcessor.cs @@ -3,13 +3,13 @@ namespace Masa.Contrib.Dispatcher.IntegrationEvents.Tests.Infrastructure; -public class CustomizeProcessor : ProcessorBase +public class CustomProcessor : ProcessorBase { public static int Times = 0; public override int Delay => 2; - public CustomizeProcessor(IServiceProvider? serviceProvider) : base(serviceProvider) + public CustomProcessor(IServiceProvider? serviceProvider) : base(serviceProvider) { } diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/IntegrationEventBusTest.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/IntegrationEventBusTest.cs index 0f69cd209..d48518d04 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/IntegrationEventBusTest.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/IntegrationEventBusTest.cs @@ -371,18 +371,18 @@ public void TestUseEventBusGetAllEventTypes() public void TestAddIntegrationEventBusReturnThrowNoImplementing() { var services = new ServiceCollection(); - Assert.ThrowsException(() => services.AddIntegrationEventBus()); + Assert.ThrowsException(() => services.AddIntegrationEventBus()); } [TestMethod] public void TestAddMultiIntegrationEventBusReturnIntegrationEventBusCountEqual1() { var services = new ServiceCollection(); - services.AddIntegrationEventBus(dispatcherOptions => + services.AddIntegrationEventBus(dispatcherOptions => { Mock publisher = new(); dispatcherOptions.Services.TryAddSingleton(publisher.Object); - }).AddIntegrationEventBus(dispatcherOptions => + }).AddIntegrationEventBus(dispatcherOptions => { Mock publisher = new(); dispatcherOptions.Services.TryAddSingleton(publisher.Object); diff --git a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/ProcessorTest.cs b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/ProcessorTest.cs index ccb543848..a2b26ac9b 100644 --- a/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/ProcessorTest.cs +++ b/test/Masa.Contrib.Dispatcher.IntegrationEvents.Tests/ProcessorTest.cs @@ -17,7 +17,7 @@ public void Initialize() { var services = new ServiceCollection(); MockPublisher(services); - services.AddIntegrationEventBus(); + services.AddIntegrationEventBus(); _serviceProvider = services.BuildServiceProvider(); _options = _serviceProvider.GetRequiredService>(); } @@ -345,8 +345,8 @@ public async Task DefaultHostedServiceTestAsync() MockPublisher(services); Mock unitOfWorkManager = new(); services.AddSingleton(_ => unitOfWorkManager.Object); - services.AddScoped(); - services.AddIntegrationEventBus(opt => + services.AddScoped(); + services.AddIntegrationEventBus(opt => { opt.CleaningLocalQueueExpireInterval = 1; opt.CleaningExpireInterval = 1; @@ -360,7 +360,7 @@ public async Task DefaultHostedServiceTestAsync() cancellationTokenSource.CancelAfter(5000); await hostedService.ExecuteAsync(cancellationTokenSource.Token); - Assert.IsTrue(CustomizeProcessor.Times > 0); + Assert.IsTrue(CustomProcessor.Times > 0); } [TestMethod] @@ -371,8 +371,8 @@ public async Task DefaultHostedServiceAndUseLoggerTestAsync() Mock unitOfWorkManager = new(); services.AddSingleton(_ => unitOfWorkManager.Object); services.AddLogging(); - services.AddScoped(); - services.AddIntegrationEventBus(opt => + services.AddScoped(); + services.AddIntegrationEventBus(opt => { opt.CleaningLocalQueueExpireInterval = 1; opt.CleaningExpireInterval = 1; @@ -386,7 +386,7 @@ public async Task DefaultHostedServiceAndUseLoggerTestAsync() cancellationTokenSource.CancelAfter(5000); await hostedService.ExecuteAsync(cancellationTokenSource.Token); - Assert.IsTrue(CustomizeProcessor.Times > 0); + Assert.IsTrue(CustomProcessor.Times > 0); } private void MockPublisher(IServiceCollection services) diff --git a/test/Masa.Contrib.Dispatcher.Tests/Infrastructure/CustomizeDbContext.cs b/test/Masa.Contrib.Dispatcher.Tests/Infrastructure/CustomDbContext.cs similarity index 68% rename from test/Masa.Contrib.Dispatcher.Tests/Infrastructure/CustomizeDbContext.cs rename to test/Masa.Contrib.Dispatcher.Tests/Infrastructure/CustomDbContext.cs index 71e4981e2..efbc24096 100644 --- a/test/Masa.Contrib.Dispatcher.Tests/Infrastructure/CustomizeDbContext.cs +++ b/test/Masa.Contrib.Dispatcher.Tests/Infrastructure/CustomDbContext.cs @@ -3,11 +3,11 @@ namespace Masa.Contrib.Dispatcher.Tests.Infrastructure; -public class CustomizeDbContext : MasaDbContext +public class CustomDbContext : MasaDbContext { public DbSet User { get; set; } - public CustomizeDbContext(MasaDbContextOptions options) : base(options) + public CustomDbContext(MasaDbContextOptions options) : base(options) { } } diff --git a/test/Masa.Contrib.Dispatcher.Tests/TestBase.cs b/test/Masa.Contrib.Dispatcher.Tests/TestBase.cs index 28e49b9d0..a2fa3fd52 100644 --- a/test/Masa.Contrib.Dispatcher.Tests/TestBase.cs +++ b/test/Masa.Contrib.Dispatcher.Tests/TestBase.cs @@ -22,15 +22,15 @@ public void Initialize() { dispatcherOptions .UseIntegrationEventBus(option => option.UseTestPub()) - .UseEventLog() + .UseEventLog() .UseEventBus(eventBusBuilder => eventBusBuilder.UseMiddleware(typeof(RecordMiddleware<>)).UseMiddleware(typeof(ValidatorMiddleware<>))) - .UseUoW(optionBuilder => + .UseUoW(optionBuilder => { optionBuilder.UseTestSqlite($"data source=disabled-soft-delete-db-{Guid.NewGuid()}").UseTestFilter(); }) - .UseRepository(); + .UseRepository(); }); - var dbContext = ServiceProvider.GetRequiredService(); + var dbContext = ServiceProvider.GetRequiredService(); dbContext.Database.EnsureCreated(); } } diff --git a/test/Masa.Contrib.Dispatcher.Tests/TestDispatcher.cs b/test/Masa.Contrib.Dispatcher.Tests/TestDispatcher.cs index f6d26a576..157916e38 100644 --- a/test/Masa.Contrib.Dispatcher.Tests/TestDispatcher.cs +++ b/test/Masa.Contrib.Dispatcher.Tests/TestDispatcher.cs @@ -18,7 +18,7 @@ public async Task TestEventReturnNotUseTranscationAsync() }; await eventBus.PublishAsync(@event); - var dbContext = serviceProvider.GetRequiredService(); + var dbContext = serviceProvider.GetRequiredService(); Assert.IsTrue(dbContext.Set().Count() == 1); } @@ -37,7 +37,7 @@ public async Task TestCommandReturnUseTransacationAndTimeEqual1Async() Assert.IsTrue(RecordMiddleware.Time == 1); Assert.IsTrue(RecordMiddleware.Time == 0); - var dbContext = serviceProvider.GetRequiredService(); + var dbContext = serviceProvider.GetRequiredService(); Assert.IsTrue(dbContext.Set().Count() == 1); } @@ -46,7 +46,7 @@ public async Task TestQueryReturnNameIsRequiredOnCheckUserQueryAsync() { var serviceProvider = ServiceProvider; var eventBus = serviceProvider.GetRequiredService(); - var dbContext = serviceProvider.GetRequiredService(); + var dbContext = serviceProvider.GetRequiredService(); await dbContext.Set().AddAsync(new User() { Name = "Tom", diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/AutomaticCallerTest.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/AutomaticCallerTest.cs index 621ac7bfd..2b97c2fd9 100644 --- a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/AutomaticCallerTest.cs +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/AutomaticCallerTest.cs @@ -1,6 +1,8 @@ // Copyright (c) MASA Stack All rights reserved. // Licensed under the MIT License. See LICENSE.txt in the project root for license information. +using DaprCaller = Masa.Contrib.Service.Caller.AutomaticCaller.Tests.Callers.DaprCaller; + namespace Masa.Contrib.Service.Caller.AutomaticCaller.Tests; [TestClass] diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/CallerTest.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/CallerTest.cs index 892278925..d06e3220e 100644 --- a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/CallerTest.cs +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/CallerTest.cs @@ -20,8 +20,8 @@ public void TestCallerProviderServiceLifetime() }); }); var serviceProvider = services.BuildServiceProvider(); - var callerProvider1 = serviceProvider.GetRequiredService(); - var callerProvider2 = serviceProvider.GetRequiredService(); + var callerProvider1 = serviceProvider.GetRequiredService(); + var callerProvider2 = serviceProvider.GetRequiredService(); Assert.IsTrue(callerProvider1 == callerProvider2); } @@ -44,12 +44,12 @@ public void TestCaller() }); }); var serviceProvider = services.BuildServiceProvider(); - var callerProvider = serviceProvider.GetRequiredService(); - Assert.IsNotNull(callerProvider); + var caller = serviceProvider.GetRequiredService(); + Assert.IsNotNull(caller); - var caller = serviceProvider.GetRequiredService().CreateClient(); - var daprCaller = serviceProvider.GetRequiredService().CreateClient("dapr"); - var httpCaller = serviceProvider.GetRequiredService().CreateClient("http"); + caller = serviceProvider.GetRequiredService().Create(); + var daprCaller = serviceProvider.GetRequiredService().Create("dapr"); + var httpCaller = serviceProvider.GetRequiredService().Create("http"); Assert.IsTrue(caller.GetType().FullName != daprCaller.GetType().FullName); Assert.IsTrue(caller.GetType().FullName == httpCaller.GetType().FullName); @@ -208,7 +208,7 @@ public void TestAddMultiCaller() }); }); var serviceProvider = services.BuildServiceProvider(); - Assert.IsNotNull(serviceProvider.GetRequiredService().CreateClient("masastack")); - Assert.IsNotNull(serviceProvider.GetRequiredService().CreateClient("masastack2")); + Assert.IsNotNull(serviceProvider.GetRequiredService().Create("masastack")); + Assert.IsNotNull(serviceProvider.GetRequiredService().Create("masastack2")); } } diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/DaprCaller.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/DaprCaller.cs index a3662f200..81e897073 100644 --- a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/DaprCaller.cs +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/DaprCaller.cs @@ -12,5 +12,5 @@ public DaprCaller(IServiceProvider serviceProvider) : base(serviceProvider) protected override string AppId { get; set; } - public bool CallerProviderIsNotNull() => CallerProvider != null; + public bool CallerProviderIsNotNull() => Caller != null; } diff --git a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/GithubCaller.cs b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/GithubCaller.cs index d10a461a5..be4b15673 100644 --- a/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/GithubCaller.cs +++ b/test/Masa.Contrib.Service.Caller.AutomaticCaller.Tests/Callers/GithubCaller.cs @@ -14,7 +14,7 @@ public GithubCaller(IServiceProvider serviceProvider) : base(serviceProvider) public async Task GetAsync() { - var res = await CallerProvider.GetAsync(""); + var res = await Caller.GetAsync(""); return res.IsSuccessStatusCode && res.StatusCode == HttpStatusCode.OK; } } diff --git a/test/Masa.Contrib.Service.Caller.Tests/CallerTest.cs b/test/Masa.Contrib.Service.Caller.Tests/CallerTest.cs index 657779c11..7ea75089e 100644 --- a/test/Masa.Contrib.Service.Caller.Tests/CallerTest.cs +++ b/test/Masa.Contrib.Service.Caller.Tests/CallerTest.cs @@ -27,20 +27,20 @@ public async Task TestGetAsync() }); _ = _builder.Build(); var serviceProvider = _builder.Services.BuildServiceProvider(); - var githubCaller = serviceProvider.GetRequiredService(); + var githubCaller = serviceProvider.GetRequiredService(); Assert.IsTrue(await GetAsync(githubCaller)); } - private async Task GetAsync(ICallerProvider callerProvider) + private async Task GetAsync(ICaller caller) { - var res = await callerProvider.GetAsync(""); + var res = await caller.GetAsync(""); return res.IsSuccessStatusCode && res.StatusCode == HttpStatusCode.OK; } [TestMethod] public void TestConvertToDictionaryByDynamic() { - var provider = new DefaultTypeConvertProvider(); + var provider = new DefaultTypeConvert(); var dictionary = new Dictionary { { "account", "jim" }, @@ -58,7 +58,7 @@ public void TestConvertToDictionaryByDynamic() [TestMethod] public void TestConvertToDictionaryByObject() { - var provider = new DefaultTypeConvertProvider(); + var provider = new DefaultTypeConvert(); var query = new UserListQuery("Jim"); var dictionary = new Dictionary { @@ -71,7 +71,7 @@ public void TestConvertToDictionaryByObject() [TestMethod] public void TestConvertToDictionaryByObject2() { - var provider = new DefaultTypeConvertProvider(); + var provider = new DefaultTypeConvert(); var query = new UserDetailQuery("Jim", "Music", "Game"); var result = provider.ConvertToDictionary(query); Assert.IsTrue(result.Count == 2); @@ -86,7 +86,7 @@ public void TestConvertToDictionaryByObject2() [TestMethod] public void TestConvertToDictionaryByObject3() { - var provider = new DefaultTypeConvertProvider(); + var provider = new DefaultTypeConvert(); List tags = null!; var query = new UserDetailQuery("Jim", tags); @@ -99,7 +99,7 @@ public void TestConvertToDictionaryByObject3() [TestMethod] public void TestConvertToDictionaryByObject4() { - var provider = new DefaultTypeConvertProvider(); + var provider = new DefaultTypeConvert(); var query = new UserDetailQuery(null!, "Music", "Game"); var result = provider.ConvertToDictionary(query); Assert.IsTrue(result.Count == 1); @@ -113,7 +113,7 @@ public void TestConvertToDictionaryByObject4() [TestMethod] public void TestConvertToDictionaryByObject5() { - var provider = new DefaultTypeConvertProvider(); + var provider = new DefaultTypeConvert(); var dic = new Dictionary() { { "Account", "Jim" } @@ -126,7 +126,7 @@ public void TestConvertToDictionaryByObject5() [TestMethod] public void TestConvertToDictionaryByObject6() { - var provider = new DefaultTypeConvertProvider(); + var provider = new DefaultTypeConvert(); var dic = new List>() { new("Account", "Jim") diff --git a/test/Masa.Contrib.Service.Caller.Tests/CustomHttpClientCallerProvider.cs b/test/Masa.Contrib.Service.Caller.Tests/CustomHttpClientCaller.cs similarity index 66% rename from test/Masa.Contrib.Service.Caller.Tests/CustomHttpClientCallerProvider.cs rename to test/Masa.Contrib.Service.Caller.Tests/CustomHttpClientCaller.cs index a1273f851..aeb1a890f 100644 --- a/test/Masa.Contrib.Service.Caller.Tests/CustomHttpClientCallerProvider.cs +++ b/test/Masa.Contrib.Service.Caller.Tests/CustomHttpClientCaller.cs @@ -3,9 +3,9 @@ namespace Masa.Contrib.Service.Caller.Tests; -public class CustomHttpClientCallerProvider : HttpClientCallerProvider +public class CustomHttpClientCaller : HttpClientCaller { - public CustomHttpClientCallerProvider(IServiceProvider serviceProvider, string name, string baseApi) + public CustomHttpClientCaller(IServiceProvider serviceProvider, string name, string baseApi) : base(serviceProvider, name, baseApi) { } diff --git a/test/Masa.Contrib.Service.Caller.Tests/HttpClientCallerTest.cs b/test/Masa.Contrib.Service.Caller.Tests/HttpClientCallerTest.cs index 433247909..0c297fb59 100644 --- a/test/Masa.Contrib.Service.Caller.Tests/HttpClientCallerTest.cs +++ b/test/Masa.Contrib.Service.Caller.Tests/HttpClientCallerTest.cs @@ -31,15 +31,15 @@ public void TestGetRequestUri(string prefix, string methods, string result) var services = new ServiceCollection(); services.AddCaller(opt => opt.UseHttpClient()); var serviceProvider = services.BuildServiceProvider(); - var provider = new CustomHttpClientCallerProvider(serviceProvider, string.Empty, prefix); - Assert.IsTrue(provider.GetResult(methods) == result); + var caller = new CustomHttpClientCaller(serviceProvider, string.Empty, prefix); + Assert.IsTrue(caller.GetResult(methods) == result); } [TestMethod] public async Task TestRequestDataIsXmlAsync() { var services = new ServiceCollection(); - services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); Mock httpClientFactory = new(); @@ -66,11 +66,11 @@ public async Task TestRequestDataIsXmlAsync() httpClientFactory.Setup(factory => factory.CreateClient(It.IsAny())).Returns(magicHttpClient); services.AddSingleton(httpClientFactory.Object); var serviceProvider = services.BuildServiceProvider(); - string name = ""; + string name = ""; string prefix = ""; - var httpClientCallerProvider = new HttpClientCallerProvider(serviceProvider, name, prefix); + var caller = new HttpClientCaller(serviceProvider, name, prefix); - var res = await httpClientCallerProvider.PostAsync("Hello", new RegisterUser("Jim", "123456")); + var res = await caller.PostAsync("Hello", new RegisterUser("Jim", "123456")); Assert.IsNotNull(res); Assert.IsTrue(res.Code == response.Code); } @@ -81,7 +81,7 @@ public async Task TestRequestMessageReturnOnceAsync() var services = new ServiceCollection(); RegisterUser registerUser = new RegisterUser("Jim", "123456"); - services.AddSingleton(); + services.AddSingleton(); Mock requestMessage = new(); requestMessage.Setup(req => req.ProcessHttpRequestMessageAsync(It.IsAny())) .ReturnsAsync(new HttpRequestMessage(HttpMethod.Post, "Hello")).Verifiable(); @@ -116,11 +116,11 @@ public async Task TestRequestMessageReturnOnceAsync() httpClientFactory.Setup(factory => factory.CreateClient(It.IsAny())).Returns(magicHttpClient); services.AddSingleton(httpClientFactory.Object); var serviceProvider = services.BuildServiceProvider(); - string name = ""; + string name = ""; string prefix = ""; - var httpClientCallerProvider = new HttpClientCallerProvider(serviceProvider, name, prefix); + var caller = new HttpClientCaller(serviceProvider, name, prefix); - var res = await httpClientCallerProvider.PostAsync("Hello", registerUser); + var res = await caller.PostAsync("Hello", registerUser); Assert.IsNotNull(res); Assert.IsTrue(res.Code == response.Code); requestMessage.Verify(r => r.ProcessHttpRequestMessageAsync(It.IsAny(), It.IsAny()), Times.Once); diff --git a/test/Masa.Contrib.Service.Caller.Tests/TypeConvertTest.cs b/test/Masa.Contrib.Service.Caller.Tests/TypeConvertTest.cs index 3b06891f3..ddbdcd8d6 100644 --- a/test/Masa.Contrib.Service.Caller.Tests/TypeConvertTest.cs +++ b/test/Masa.Contrib.Service.Caller.Tests/TypeConvertTest.cs @@ -9,7 +9,7 @@ public class TypeConvertTest [TestMethod] public void TestConvertToKeyValuePairs() { - var defaultTypeConvertProvider = new DefaultTypeConvertProvider(); + var defaultTypeConvertProvider = new DefaultTypeConvert(); var result = defaultTypeConvertProvider.ConvertToKeyValuePairs(new { id = 1, diff --git a/test/Masa.Contrib.Service.Caller.Tests/Utils/XmlUtils.cs b/test/Masa.Contrib.Service.Caller.Tests/Utils/XmlUtils.cs index 86bbfbdb3..497e57960 100644 --- a/test/Masa.Contrib.Service.Caller.Tests/Utils/XmlUtils.cs +++ b/test/Masa.Contrib.Service.Caller.Tests/Utils/XmlUtils.cs @@ -1,9 +1,12 @@ // Copyright (c) MASA Stack All rights reserved. // Licensed under the MIT License. See LICENSE.txt in the project root for license information. -namespace Masa.Contrib.Service.Caller.Tests.Utils; +namespace Masa.Contrib.Service.Caller.Tests; -public class XmlUtils +/// +/// Temporary use, later versions will be removed +/// +internal class XmlUtils { public static string Serializer(object data) { diff --git a/test/Masa.Contrib.Service.Caller.Tests/XmlRequestMessage.cs b/test/Masa.Contrib.Service.Caller.Tests/XmlRequestMessage.cs deleted file mode 100644 index dbdfb93b9..000000000 --- a/test/Masa.Contrib.Service.Caller.Tests/XmlRequestMessage.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.Service.Caller.Tests; - -public class XmlRequestMessage : IRequestMessage -{ - public Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage) - => Task.FromResult(requestMessage); - - public Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage, TRequest data) - { - var xmlContent = XmlUtils.Serializer(data!); - requestMessage.Content = new StringContent(xmlContent); - return Task.FromResult(requestMessage); - } -} diff --git a/test/Masa.Contrib.Service.Caller.Tests/_Imports.cs b/test/Masa.Contrib.Service.Caller.Tests/_Imports.cs index 7a92e736e..a406d75ab 100644 --- a/test/Masa.Contrib.Service.Caller.Tests/_Imports.cs +++ b/test/Masa.Contrib.Service.Caller.Tests/_Imports.cs @@ -6,7 +6,6 @@ global using Masa.Contrib.Service.Caller.Tests.Queries; global using Masa.Contrib.Service.Caller.Tests.Requesties; global using Masa.Contrib.Service.Caller.Tests.Response; -global using Masa.Contrib.Service.Caller.Tests.Utils; global using Masa.Utils.Exceptions; global using Microsoft.AspNetCore.Builder; global using Microsoft.Extensions.DependencyInjection; diff --git a/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomizeCredentialProvider.cs b/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomCredentialProvider.cs similarity index 91% rename from test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomizeCredentialProvider.cs rename to test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomCredentialProvider.cs index ca1caeb49..a3990698d 100644 --- a/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomizeCredentialProvider.cs +++ b/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomCredentialProvider.cs @@ -3,7 +3,7 @@ namespace Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests; -public class CustomizeCredentialProvider : DefaultCredentialProvider +public class CustomCredentialProvider : DefaultCredentialProvider { public readonly TemporaryCredentialsResponse TemporaryCredentials = new( "accessKeyId", @@ -11,7 +11,7 @@ public class CustomizeCredentialProvider : DefaultCredentialProvider "sessionToken", DateTime.UtcNow.AddHours(-1)); - public CustomizeCredentialProvider(IOssClientFactory ossClientFactory, + public CustomCredentialProvider(IOssClientFactory ossClientFactory, IAliyunStorageOptionProvider optionProvider, IMemoryCache cache, ILogger? logger) diff --git a/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomizeNullClient.cs b/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomNullClient.cs similarity index 86% rename from test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomizeNullClient.cs rename to test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomNullClient.cs index 19cf9a4a2..9d7b59734 100644 --- a/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomizeNullClient.cs +++ b/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomNullClient.cs @@ -3,7 +3,7 @@ namespace Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests; -public class CustomizeNullClient : DefaultCredentialProvider +public class CustomNullClient : DefaultCredentialProvider { public string Message = "You are not authorized to do this action. You should be authorized by RAM."; @@ -17,7 +17,7 @@ public override TemporaryCredentialsResponse GetTemporaryCredentials( long durationSeconds) => throw new Exception(Message); - public CustomizeNullClient(IOssClientFactory ossClientFactory, + public CustomNullClient(IOssClientFactory ossClientFactory, IAliyunStorageOptionProvider optionProvider, IMemoryCache cache, ILogger? logger = null) diff --git a/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomizeClient.cs b/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomizeClient.cs index 13b03629f..d4ec8a68c 100644 --- a/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomizeClient.cs +++ b/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/CustomizeClient.cs @@ -3,11 +3,11 @@ namespace Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests; -public class CustomizeClient : DefaultStorageClient +public class CustomClient : DefaultStorageClient { public Mock? Oss; - public CustomizeClient(ICredentialProvider credentialProvider, + public CustomClient(ICredentialProvider credentialProvider, IAliyunStorageOptionProvider optionProvider, ILogger? logger) : base(credentialProvider, optionProvider, logger) diff --git a/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/TestClient.cs b/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/TestClient.cs index 72a347e5c..77f36058c 100644 --- a/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/TestClient.cs +++ b/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/TestClient.cs @@ -6,14 +6,14 @@ namespace Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests; [TestClass] public class TestClient : BaseTest { - private CustomizeClient _client; + private CustomClient _client; [TestInitialize] public void Initialize() { Mock credentialProvider = new Mock(); Mock optionProvider = MockOptionProvider(true); - _client = new CustomizeClient(credentialProvider.Object, optionProvider.Object, NullLogger.Instance); + _client = new CustomClient(credentialProvider.Object, optionProvider.Object, NullLogger.Instance); } [TestMethod] diff --git a/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/TestCredentialProvider.cs b/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/TestCredentialProvider.cs index a241a9ab3..e42235bfc 100644 --- a/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/TestCredentialProvider.cs +++ b/test/Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests/TestCredentialProvider.cs @@ -15,7 +15,7 @@ public void TestGetSecurityTokenByCacheNotFoundReturnSuccess() var serviceProvider = services.BuildServiceProvider(); var memoryCache = serviceProvider.GetRequiredService(); - var client = new CustomizeCredentialProvider(serviceProvider.GetRequiredService(), + var client = new CustomCredentialProvider(serviceProvider.GetRequiredService(), MockOptionProvider().Object, memoryCache, NullLogger.Instance); @@ -35,7 +35,7 @@ public void TestGetSecurityTokenByCacheNotFoundAndGetTemporaryCredentialsIsNullR services.AddSingleton(); var serviceProvider = services.BuildServiceProvider(); var memoryCache = serviceProvider.GetRequiredService(); - var client = new CustomizeNullClient(serviceProvider.GetRequiredService(), + var client = new CustomNullClient(serviceProvider.GetRequiredService(), MockOptionProvider().Object, memoryCache, NullLogger.Instance); @@ -51,7 +51,7 @@ public void TestSetTemporaryCredentialsAndExpirationLessThan10SecondsReturnSkip( services.AddSingleton(); var serviceProvider = services.BuildServiceProvider(); var memoryCache = serviceProvider.GetRequiredService(); - var client = new CustomizeCredentialProvider(serviceProvider.GetRequiredService(), + var client = new CustomCredentialProvider(serviceProvider.GetRequiredService(), MockOptionProvider().Object, memoryCache, NullLogger.Instance); @@ -69,7 +69,7 @@ public void TestSetTemporaryCredentialsAndExpirationGreatherThanOrEqual10Seconds services.AddSingleton(); var serviceProvider = services.BuildServiceProvider(); var memoryCache = serviceProvider.GetRequiredService(); - var client = new CustomizeCredentialProvider(serviceProvider.GetRequiredService(), + var client = new CustomCredentialProvider(serviceProvider.GetRequiredService(), MockOptionProvider().Object, memoryCache, NullLogger.Instance); @@ -86,7 +86,7 @@ public void TestGetTemporaryCredentialsReturnNull() services.AddSingleton(); var serviceProvider = services.BuildServiceProvider(); var memoryCache = serviceProvider.GetRequiredService(); - var client = new CustomizeCredentialProvider(serviceProvider.GetRequiredService(), + var client = new CustomCredentialProvider(serviceProvider.GetRequiredService(), MockOptionProvider().Object, memoryCache, NullLogger.Instance); @@ -108,7 +108,7 @@ public void TestGetTemporaryCredentialsAndNullLoggerReturnThrowException() services.AddSingleton(); var serviceProvider = services.BuildServiceProvider(); var memoryCache = serviceProvider.GetRequiredService(); - var client = new CustomizeCredentialProvider(serviceProvider.GetRequiredService(), + var client = new CustomCredentialProvider(serviceProvider.GetRequiredService(), MockOptionProvider().Object, memoryCache, NullLogger.Instance); From 422cce76771a8b37c4ff5bb136446e37ab16f19d Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Fri, 29 Jul 2022 13:14:39 +0800 Subject: [PATCH 10/13] feat: Delete IdGenerator --- .../DefaultRequestIdGenerator.cs | 9 --------- .../Masa.Contrib.Service.Caller/IRequestIdGenerator.cs | 9 --------- 2 files changed, 18 deletions(-) delete mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestIdGenerator.cs delete mode 100644 src/Service/Caller/Masa.Contrib.Service.Caller/IRequestIdGenerator.cs diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestIdGenerator.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestIdGenerator.cs deleted file mode 100644 index 332566560..000000000 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestIdGenerator.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.Service.Caller; - -public class DefaultRequestIdGenerator : IRequestIdGenerator2 -{ - public string NewId() => Guid.NewGuid().ToString(); -} diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/IRequestIdGenerator.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/IRequestIdGenerator.cs deleted file mode 100644 index 71ca06f4d..000000000 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/IRequestIdGenerator.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.Service.Caller; - -public interface IRequestIdGenerator2 -{ - string NewId(); -} From 366bce3cfa0d02d247706b15783f841418cfef9a Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Fri, 29 Jul 2022 13:23:20 +0800 Subject: [PATCH 11/13] chore: TryOrUpdateCallerOptions rename to TryOrUpdate --- .../ServiceCollectionExtensions.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/ServiceCollectionExtensions.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/ServiceCollectionExtensions.cs index 69acf112e..a3d5a051d 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/ServiceCollectionExtensions.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/ServiceCollectionExtensions.cs @@ -32,7 +32,7 @@ public static IServiceCollection AddCaller(this IServiceCollection services, Act services.TryAddSingleton(); services.AddAutomaticCaller(callerOption); - TryOrUpdateCallerOptions(services, callerOption); + TryOrUpdate(services, callerOption); return services; } @@ -72,7 +72,7 @@ private static void AddAutomaticCaller(this IServiceCollection services, CallerO }); } - private static IServiceCollection TryOrUpdateCallerOptions(this IServiceCollection services, CallerOptions options) + private static IServiceCollection TryOrUpdate(this IServiceCollection services, CallerOptions options) { services.Configure(callerOptions => { From e3fe2be20cdd61beec1e6771ff81cff4eba7e7c4 Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Fri, 29 Jul 2022 13:30:03 +0800 Subject: [PATCH 12/13] test(Caller): Fix unit test errors --- .../ServiceCollectionExtensions.cs | 1 - .../DefaultRequestMessage.cs | 10 +++++----- .../Masa.Contrib.Service.Caller/JsonRequestMessage.cs | 4 ++-- .../Masa.Contrib.Service.Caller/XmlRequestMessage.cs | 2 +- 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/ServiceCollectionExtensions.cs b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/ServiceCollectionExtensions.cs index 4f27418d7..a624dafbc 100644 --- a/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/ServiceCollectionExtensions.cs +++ b/src/BasicAbility/Masa.Contrib.BasicAbility.Scheduler/ServiceCollectionExtensions.cs @@ -12,7 +12,6 @@ public static IServiceCollection AddSchedulerClient(this IServiceCollection serv throw new ArgumentNullException(nameof(schedulerServiceBaseAddress)); } - services.AddSingleton(); return services.AddSchedulerClient(callerOptions => { callerOptions.UseHttpClient(builder => diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs index d53525025..09a3ea7c2 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs @@ -8,15 +8,15 @@ public abstract class DefaultRequestMessage protected readonly IServiceProvider ServiceProvider; private readonly string _requestIdKey; private readonly IHttpContextAccessor? _httpContextAccessor; - protected readonly CallerFactoryOptions Options; + protected readonly CallerFactoryOptions? Options; public DefaultRequestMessage(IServiceProvider serviceProvider, - IOptions options) + IOptions? options = null) { ServiceProvider = serviceProvider; _httpContextAccessor = ServiceProvider.GetService(); - Options = options.Value; - _requestIdKey = Options.RequestIdKey ?? "Masa-Request-Id"; + Options = options?.Value; + _requestIdKey = Options?.RequestIdKey ?? "Masa-Request-Id"; } protected virtual void TrySetRequestId(HttpRequestMessage requestMessage) @@ -26,7 +26,7 @@ protected virtual void TrySetRequestId(HttpRequestMessage requestMessage) return; if (!httpContext.Request.Headers.TryGetValue(_requestIdKey, out var requestId)) - requestId = Options.IdGeneratorFunc?.Invoke(ServiceProvider) ?? Guid.NewGuid().ToString(); + requestId = Options?.IdGeneratorFunc?.Invoke(ServiceProvider) ?? Guid.NewGuid().ToString(); if (requestMessage.Headers.All(h => h.Key != _requestIdKey)) requestMessage.Headers.Add(_requestIdKey, requestId.ToString()); diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs index 409b14b47..96545ebdf 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/JsonRequestMessage.cs @@ -9,10 +9,10 @@ public class JsonRequestMessage : DefaultRequestMessage, IRequestMessage public JsonRequestMessage( IServiceProvider serviceProvider, - IOptions options) + IOptions? options = null) : base(serviceProvider, options) { - _jsonSerializerOptions = Options.JsonSerializerOptions; + _jsonSerializerOptions = Options?.JsonSerializerOptions; } public virtual Task ProcessHttpRequestMessageAsync(HttpRequestMessage requestMessage) diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/XmlRequestMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/XmlRequestMessage.cs index 04c63f512..5790aa200 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/XmlRequestMessage.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/XmlRequestMessage.cs @@ -7,7 +7,7 @@ public class XmlRequestMessage : DefaultRequestMessage, IRequestMessage { public XmlRequestMessage( IServiceProvider serviceProvider, - IOptions options) + IOptions? options = null) : base(serviceProvider, options) { } From 80e993e16765dc353f624d797037babf3fc14489 Mon Sep 17 00:00:00 2001 From: zhenlei520 Date: Fri, 29 Jul 2022 14:13:24 +0800 Subject: [PATCH 13/13] refactor(Caller): Delete IdGeneratorFunc --- .../Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs index 09a3ea7c2..2d8c44fe6 100644 --- a/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs +++ b/src/Service/Caller/Masa.Contrib.Service.Caller/DefaultRequestMessage.cs @@ -26,7 +26,7 @@ protected virtual void TrySetRequestId(HttpRequestMessage requestMessage) return; if (!httpContext.Request.Headers.TryGetValue(_requestIdKey, out var requestId)) - requestId = Options?.IdGeneratorFunc?.Invoke(ServiceProvider) ?? Guid.NewGuid().ToString(); + requestId = Guid.NewGuid().ToString(); if (requestMessage.Headers.All(h => h.Key != _requestIdKey)) requestMessage.Headers.Add(_requestIdKey, requestId.ToString());