diff --git a/Util.sln b/Util.sln
index 6b5150e65..001cba2de 100644
--- a/Util.sln
+++ b/Util.sln
@@ -21,7 +21,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Util.Core.Tests", "test\Uti
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{E6328DC1-C8F0-4DC6-941F-C6CAFFF783DF}"
EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "13-Ui", "13-Ui", "{354B3720-D050-487D-A46A-22BCFEE56D43}"
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "14-Ui", "14-Ui", "{354B3720-D050-487D-A46A-22BCFEE56D43}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "01-Util.Ui", "src\Util.Ui\01-Util.Ui.csproj", "{5F7ACBE4-A1D8-4680-AA86-B87F8494BAC2}"
EndProject
@@ -31,7 +31,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Util.Ui.NgZorro.Tests", "te
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "01-Core", "01-Core", "{9BFB5DBE-8F64-45A9-BDB2-BAD91D44A4C5}"
EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "14-Ui", "14-Ui", "{DE39BB20-AE82-47C3-9141-8CFD4C673217}"
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "15-Ui", "15-Ui", "{DE39BB20-AE82-47C3-9141-8CFD4C673217}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Util.Ui.Tests", "test\Util.Ui.Tests\Util.Ui.Tests.csproj", "{766CAB38-F064-419F-837B-D6DA8B61AF66}"
EndProject
@@ -257,13 +257,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "02-Util.Images.Avatar", "sr
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Util.Images.Avatar.Tests.Integration", "test\Util.Images.Avatar.Tests.Integration\Util.Images.Avatar.Tests.Integration.csproj", "{75A31AAB-B7E6-4F13-9B7A-B74216B2EDDE}"
EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "14-Generators", "14-Generators", "{411247A4-4665-4BE6-8E5C-08F6D0BA2213}"
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "15-Generators", "15-Generators", "{411247A4-4665-4BE6-8E5C-08F6D0BA2213}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "01-Util.Generators", "src\Util.Generators\01-Util.Generators.csproj", "{36990D32-6F41-44A6-BB88-A3F15E12C35B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "02-Util.Generators.Razor", "src\Util.Generators.Razor\02-Util.Generators.Razor.csproj", "{21831A4F-B3C9-40E7-855B-75F9D679FF55}"
EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "15-Generators", "15-Generators", "{F7D4E7CB-468D-4570-8D82-D065F08BE40D}"
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "16-Generators", "16-Generators", "{F7D4E7CB-468D-4570-8D82-D065F08BE40D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Util.Generators.Tests", "test\Util.Generators.Tests\Util.Generators.Tests.csproj", "{5996F536-14B9-4F95-A18B-716E5F7EE478}"
EndProject
@@ -285,8 +285,26 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Util.Generators.Razor.Tests
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Util.Events.Tests.Integration", "test\Util.Events.Tests.Integration\Util.Events.Tests.Integration.csproj", "{FB11256C-06C0-4B24-863A-C87D78F8EE2A}"
EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "14-Microservices", "14-Microservices", "{547FD391-A56B-47A6-B20C-5FC04FA15C56}"
+EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "01-Util.Events.Abstractions", "src\Util.Events.Abstractions\01-Util.Events.Abstractions.csproj", "{6233BF36-9636-43BD-9462-2D31A05EE4ED}"
EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "13-Microservices", "13-Microservices", "{1DEC52C8-6692-4DA7-AE34-B76D728F895A}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "01-Util.Microservices", "src\Util.Microservices\01-Util.Microservices.csproj", "{F8417623-6936-43C4-A967-9D6BD002AD16}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "03-Util.Microservices.Dapr", "src\Util.Microservices.Dapr\03-Util.Microservices.Dapr.csproj", "{CAA32331-4A8E-4C16-BC7D-7CA646B393F4}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Util.Microservices.Dapr.Tests.Integration", "test\Util.Microservices.Dapr.Tests.Integration\Util.Microservices.Dapr.Tests.Integration.csproj", "{08B1A026-4F8C-4336-B5B8-3189023DFF2B}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "02-Util.Microservices.Polly", "src\Util.Microservices.Polly\02-Util.Microservices.Polly.csproj", "{0BCB6FF1-E374-4AED-9888-83C7CFED0E98}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Util.Microservices.Polly.Tests.Integration", "test\Util.Microservices.Polly.Tests.Integration\Util.Microservices.Polly.Tests.Integration.csproj", "{DF1E55A5-7EA8-41B2-BEBA-72544D256069}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "04-Util.Microservices.HealthChecks", "src\Util.Microservices.HealthChecks\04-Util.Microservices.HealthChecks.csproj", "{9C58E50F-0589-4A4E-B94D-2EC0BF02F61F}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Util.Microservices.Dapr.WebApiSample", "test\Util.Microservices.Dapr.WebApiSample\Util.Microservices.Dapr.WebApiSample.csproj", "{AE19ED93-AFC4-4F91-93BD-B00D343D3BA0}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -701,6 +719,34 @@ Global
{6233BF36-9636-43BD-9462-2D31A05EE4ED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6233BF36-9636-43BD-9462-2D31A05EE4ED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6233BF36-9636-43BD-9462-2D31A05EE4ED}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F8417623-6936-43C4-A967-9D6BD002AD16}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F8417623-6936-43C4-A967-9D6BD002AD16}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F8417623-6936-43C4-A967-9D6BD002AD16}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F8417623-6936-43C4-A967-9D6BD002AD16}.Release|Any CPU.Build.0 = Release|Any CPU
+ {CAA32331-4A8E-4C16-BC7D-7CA646B393F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {CAA32331-4A8E-4C16-BC7D-7CA646B393F4}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {CAA32331-4A8E-4C16-BC7D-7CA646B393F4}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {CAA32331-4A8E-4C16-BC7D-7CA646B393F4}.Release|Any CPU.Build.0 = Release|Any CPU
+ {08B1A026-4F8C-4336-B5B8-3189023DFF2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {08B1A026-4F8C-4336-B5B8-3189023DFF2B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {08B1A026-4F8C-4336-B5B8-3189023DFF2B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {08B1A026-4F8C-4336-B5B8-3189023DFF2B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {0BCB6FF1-E374-4AED-9888-83C7CFED0E98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {0BCB6FF1-E374-4AED-9888-83C7CFED0E98}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {0BCB6FF1-E374-4AED-9888-83C7CFED0E98}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {0BCB6FF1-E374-4AED-9888-83C7CFED0E98}.Release|Any CPU.Build.0 = Release|Any CPU
+ {DF1E55A5-7EA8-41B2-BEBA-72544D256069}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {DF1E55A5-7EA8-41B2-BEBA-72544D256069}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {DF1E55A5-7EA8-41B2-BEBA-72544D256069}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {DF1E55A5-7EA8-41B2-BEBA-72544D256069}.Release|Any CPU.Build.0 = Release|Any CPU
+ {9C58E50F-0589-4A4E-B94D-2EC0BF02F61F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {9C58E50F-0589-4A4E-B94D-2EC0BF02F61F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {9C58E50F-0589-4A4E-B94D-2EC0BF02F61F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {9C58E50F-0589-4A4E-B94D-2EC0BF02F61F}.Release|Any CPU.Build.0 = Release|Any CPU
+ {AE19ED93-AFC4-4F91-93BD-B00D343D3BA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {AE19ED93-AFC4-4F91-93BD-B00D343D3BA0}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {AE19ED93-AFC4-4F91-93BD-B00D343D3BA0}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {AE19ED93-AFC4-4F91-93BD-B00D343D3BA0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -842,7 +888,16 @@ Global
{4FFD1073-9358-418D-BB4D-DB63FE0A11DF} = {445850B7-1A9D-4E9D-8AC1-765F3792DC19}
{5BFF8BA0-EA27-4493-88A5-5BC57286D536} = {F7D4E7CB-468D-4570-8D82-D065F08BE40D}
{FB11256C-06C0-4B24-863A-C87D78F8EE2A} = {3ABD7B4B-37F9-4D49-92D9-384190177286}
+ {547FD391-A56B-47A6-B20C-5FC04FA15C56} = {E6328DC1-C8F0-4DC6-941F-C6CAFFF783DF}
{6233BF36-9636-43BD-9462-2D31A05EE4ED} = {59F82491-51E3-4A12-B427-9815AEA23D10}
+ {1DEC52C8-6692-4DA7-AE34-B76D728F895A} = {C01B9930-D67F-41C5-90C9-C87DC53F39CB}
+ {F8417623-6936-43C4-A967-9D6BD002AD16} = {1DEC52C8-6692-4DA7-AE34-B76D728F895A}
+ {CAA32331-4A8E-4C16-BC7D-7CA646B393F4} = {1DEC52C8-6692-4DA7-AE34-B76D728F895A}
+ {08B1A026-4F8C-4336-B5B8-3189023DFF2B} = {547FD391-A56B-47A6-B20C-5FC04FA15C56}
+ {0BCB6FF1-E374-4AED-9888-83C7CFED0E98} = {1DEC52C8-6692-4DA7-AE34-B76D728F895A}
+ {DF1E55A5-7EA8-41B2-BEBA-72544D256069} = {547FD391-A56B-47A6-B20C-5FC04FA15C56}
+ {9C58E50F-0589-4A4E-B94D-2EC0BF02F61F} = {1DEC52C8-6692-4DA7-AE34-B76D728F895A}
+ {AE19ED93-AFC4-4F91-93BD-B00D343D3BA0} = {547FD391-A56B-47A6-B20C-5FC04FA15C56}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {94347832-A36D-4C42-9C4D-B848BD4F5DA9}
diff --git a/build/BuildScript.cs b/build/BuildScript.cs
index 04e7f1c9c..d6aa96889 100644
--- a/build/BuildScript.cs
+++ b/build/BuildScript.cs
@@ -199,6 +199,7 @@ private void PublishNuGetPackage( ITaskContext context, params ITarget[] dependT
.DoNotFailOnError( ex => { Console.WriteLine( $"Failed to publish {package}.exception: {ex.Message}" ); } )
.ServerUrl( NugetUrl )
.ApiKey( NugetApiKey )
+ .SkipDuplicate()
.Execute( context );
}
} );
diff --git a/build/version.props b/build/version.props
index 4b5a05e30..1932c79c7 100644
--- a/build/version.props
+++ b/build/version.props
@@ -2,7 +2,7 @@
7
1
- 2
+ 11
$(VersionMajor).$(VersionMinor).$(VersionPatch)
diff --git a/src/Util.Aop.AspectCore/Usings.cs b/src/Util.Aop.AspectCore/Usings.cs
index b63a1b77e..059e6cc71 100644
--- a/src/Util.Aop.AspectCore/Usings.cs
+++ b/src/Util.Aop.AspectCore/Usings.cs
@@ -1,30 +1,6 @@
global using System;
global using System.Threading.Tasks;
-global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using AspectCore.Configuration;
global using AspectCore.DynamicProxy;
global using AspectCore.DynamicProxy.Parameters;
diff --git a/src/Util.Application.EntityFrameworkCore/Usings.cs b/src/Util.Application.EntityFrameworkCore/Usings.cs
index c27b20cbe..7bf07ab32 100644
--- a/src/Util.Application.EntityFrameworkCore/Usings.cs
+++ b/src/Util.Application.EntityFrameworkCore/Usings.cs
@@ -2,29 +2,3 @@
global using System.Threading.Tasks;
global using System.Collections.Generic;
global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
-global using Microsoft.AspNetCore.Mvc;
-global using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
\ No newline at end of file
diff --git a/src/Util.Application.WebApi/Controllers/WebApiControllerBase.cs b/src/Util.Application.WebApi/Controllers/WebApiControllerBase.cs
index 3e30ced05..e2cd178b3 100644
--- a/src/Util.Application.WebApi/Controllers/WebApiControllerBase.cs
+++ b/src/Util.Application.WebApi/Controllers/WebApiControllerBase.cs
@@ -1,10 +1,11 @@
using Util.Applications.Filters;
+using Util.AspNetCore;
using Util.Helpers;
using Util.Logging;
using Util.Properties;
using Util.Sessions;
-namespace Util.Applications.Controllers;
+namespace Util.Applications.Controllers;
///
/// WebApi控制器基类
@@ -47,10 +48,20 @@ protected virtual IActionResult Success( dynamic data = null, string message = n
/// 获取结果
///
private IActionResult GetResult( string code, string message, dynamic data, int? httpStatusCode ) {
+ var options = GetJsonSerializerOptions();
var resultFactory = HttpContext.RequestServices.GetService();
if ( resultFactory == null )
- return new Result( code, message, data, httpStatusCode );
- return resultFactory.CreateResult( code, message, data, httpStatusCode );
+ return new Result( code, message, data, httpStatusCode, options );
+ return resultFactory.CreateResult( code, message, data, httpStatusCode, options );
+ }
+
+ ///
+ /// 获取Json序列化配置
+ ///
+ private JsonSerializerOptions GetJsonSerializerOptions() {
+ var factory = HttpContext.RequestServices.GetService();
+ factory.CheckNull( nameof( factory ) );
+ return factory.CreateOptions();
}
///
diff --git a/src/Util.Application.WebApi/Filters/ExceptionHandlerAttribute.cs b/src/Util.Application.WebApi/Filters/ExceptionHandlerAttribute.cs
index 4c6b8bd29..f66f4646b 100644
--- a/src/Util.Application.WebApi/Filters/ExceptionHandlerAttribute.cs
+++ b/src/Util.Application.WebApi/Filters/ExceptionHandlerAttribute.cs
@@ -1,5 +1,6 @@
using Util.Helpers;
using Util.Exceptions;
+using Util.AspNetCore;
namespace Util.Applications.Filters;
@@ -39,14 +40,23 @@ protected virtual string GetLocalizedMessages( ExceptionContext context, string
return stringLocalizer[message];
}
-
///
/// 获取结果
///
protected virtual IActionResult GetResult( ExceptionContext context, string code, string message, int? httpStatusCode ) {
+ var options = GetJsonSerializerOptions( context );
var resultFactory = context.HttpContext.RequestServices.GetService();
if ( resultFactory == null )
- return new Result( code, message, null, httpStatusCode );
- return resultFactory.CreateResult( code, message, null, httpStatusCode );
+ return new Result( code, message, null, httpStatusCode, options );
+ return resultFactory.CreateResult( code, message, null, httpStatusCode, options );
+ }
+
+ ///
+ /// 获取Json序列化配置
+ ///
+ private JsonSerializerOptions GetJsonSerializerOptions( ExceptionContext context ) {
+ var factory = context.HttpContext.RequestServices.GetService();
+ factory.CheckNull( nameof( factory ) );
+ return factory.CreateOptions();
}
}
\ No newline at end of file
diff --git a/src/Util.Application.WebApi/Filters/LockAttribute.cs b/src/Util.Application.WebApi/Filters/LockAttribute.cs
index 800c53fad..11bd62a68 100644
--- a/src/Util.Application.WebApi/Filters/LockAttribute.cs
+++ b/src/Util.Application.WebApi/Filters/LockAttribute.cs
@@ -1,4 +1,5 @@
using Util.Applications.Locks;
+using Util.AspNetCore;
using Util.Helpers;
using Util.Properties;
using Util.Sessions;
@@ -89,10 +90,20 @@ protected string GetUserId( ActionExecutingContext context ) {
/// 获取结果
///
private IActionResult GetResult( ActionExecutingContext context,string code, string message ) {
+ var options = GetJsonSerializerOptions( context );
var resultFactory = context.HttpContext.RequestServices.GetService();
if ( resultFactory == null )
- return new Result( code, message );
- return resultFactory.CreateResult( code, message, null, null );
+ return new Result( code, message,options: options );
+ return resultFactory.CreateResult( code, message, null, null, options );
+ }
+
+ ///
+ /// 获取Json序列化配置
+ ///
+ private JsonSerializerOptions GetJsonSerializerOptions( ActionExecutingContext context ) {
+ var factory = context.HttpContext.RequestServices.GetService();
+ factory.CheckNull( nameof( factory ) );
+ return factory.CreateOptions();
}
///
diff --git a/src/Util.Application.WebApi/IResultFactory.cs b/src/Util.Application.WebApi/IResultFactory.cs
index 01db4318f..072e5ecab 100644
--- a/src/Util.Application.WebApi/IResultFactory.cs
+++ b/src/Util.Application.WebApi/IResultFactory.cs
@@ -13,5 +13,6 @@ public interface IResultFactory : ISingletonDependency {
/// 消息
/// 数据
/// Http状态码
- IActionResult CreateResult( string code, string message, dynamic data, int? httpStatusCode );
+ /// Json序列化配置
+ IActionResult CreateResult( string code, string message, dynamic data, int? httpStatusCode, JsonSerializerOptions options );
}
\ No newline at end of file
diff --git a/src/Util.Application.WebApi/Infrastructure/WebApiServiceRegistrar.cs b/src/Util.Application.WebApi/Infrastructure/WebApiServiceRegistrar.cs
index 078f2db0f..ed1438868 100644
--- a/src/Util.Application.WebApi/Infrastructure/WebApiServiceRegistrar.cs
+++ b/src/Util.Application.WebApi/Infrastructure/WebApiServiceRegistrar.cs
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Http;
using Util.Applications.Logging;
+using Util.AspNetCore;
using Util.Infrastructure;
using Util.Logging;
@@ -89,9 +90,19 @@ protected virtual string GetLocalizedMessages( HttpContext context, string messa
/// 获取结果
///
protected virtual IActionResult GetResult( HttpContext context, string code, string message, int? httpStatusCode ) {
+ var options = GetJsonSerializerOptions( context );
var resultFactory = context.RequestServices.GetService();
if ( resultFactory == null )
- return new Result( code, message, null, httpStatusCode );
- return resultFactory.CreateResult( code, message, null, httpStatusCode );
+ return new Result( code, message, null, httpStatusCode, options );
+ return resultFactory.CreateResult( code, message, null, httpStatusCode, options );
+ }
+
+ ///
+ /// 获取Json序列化配置
+ ///
+ private JsonSerializerOptions GetJsonSerializerOptions( HttpContext context ) {
+ var factory = context.RequestServices.GetService();
+ factory.CheckNull( nameof( factory ) );
+ return factory.CreateOptions();
}
}
\ No newline at end of file
diff --git a/src/Util.Application.WebApi/JsonSerializerOptionsFactory.cs b/src/Util.Application.WebApi/JsonSerializerOptionsFactory.cs
new file mode 100644
index 000000000..28ce48da5
--- /dev/null
+++ b/src/Util.Application.WebApi/JsonSerializerOptionsFactory.cs
@@ -0,0 +1,24 @@
+using Util.AspNetCore;
+using Util.SystemTextJson;
+
+namespace Util.Applications;
+
+///
+/// Json序列化配置工厂
+///
+public class JsonSerializerOptionsFactory : IJsonSerializerOptionsFactory {
+ ///
+ /// 创建Json序列化配置
+ ///
+ public JsonSerializerOptions CreateOptions() {
+ return new JsonSerializerOptions {
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
+ Encoder = JavaScriptEncoder.Create( UnicodeRanges.All ),
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ Converters = {
+ new DateTimeJsonConverter(),
+ new NullableDateTimeJsonConverter()
+ }
+ };
+ }
+}
\ No newline at end of file
diff --git a/src/Util.Application.WebApi/Result.cs b/src/Util.Application.WebApi/Result.cs
index ffcf89d1e..cb14d47f5 100644
--- a/src/Util.Application.WebApi/Result.cs
+++ b/src/Util.Application.WebApi/Result.cs
@@ -26,19 +26,30 @@ public class Result : JsonResult {
/// 消息
/// 数据
/// Http状态码
- public Result( string code, string message, dynamic data = null, int? httpStatusCode = null ) : base( null ) {
+ /// Json序列化配置
+ public Result( string code, string message, dynamic data = null, int? httpStatusCode = null, JsonSerializerOptions options = null ) : base( null ) {
Code = code;
Message = message;
Data = data;
- SerializerSettings = new JsonSerializerOptions {
+ SerializerSettings = GetOptions( options );
+ StatusCode = httpStatusCode;
+ }
+
+ ///
+ /// 获取Json序列化配置
+ ///
+ private JsonSerializerOptions GetOptions( JsonSerializerOptions options ) {
+ if ( options != null )
+ return options;
+ return new JsonSerializerOptions {
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Encoder = JavaScriptEncoder.Create( UnicodeRanges.All ),
- Converters = {
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ Converters = {
new DateTimeJsonConverter(),
new NullableDateTimeJsonConverter()
}
};
- StatusCode = httpStatusCode;
}
///
diff --git a/src/Util.Application.WebApi/Usings.cs b/src/Util.Application.WebApi/Usings.cs
index 7796c168f..e176120dc 100644
--- a/src/Util.Application.WebApi/Usings.cs
+++ b/src/Util.Application.WebApi/Usings.cs
@@ -2,32 +2,17 @@
global using System.Threading.Tasks;
global using System.Collections.Generic;
global using System.Linq;
-global using System.Threading;
global using System.Diagnostics;
-global using System.Text;
global using System.IO;
global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
+global using System.Text.Json.Serialization;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Microsoft.AspNetCore.Mvc;
-global using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
global using Microsoft.AspNetCore.Mvc.Filters;
global using Microsoft.Extensions.Localization;
global using Microsoft.AspNetCore.Hosting;
diff --git a/src/Util.Application/ExceptionExtensions.cs b/src/Util.Application/ExceptionExtensions.cs
index ffd80cddd..f575425f9 100644
--- a/src/Util.Application/ExceptionExtensions.cs
+++ b/src/Util.Application/ExceptionExtensions.cs
@@ -1,70 +1,70 @@
-using Util.Exceptions;
-using Util.Properties;
-
-namespace Util.Applications;
-
-///
-/// 异常扩展
-///
-public static class ExceptionExtensions {
- ///
- /// 获取原始异常
- ///
- /// 异常
- public static Exception GetRawException( this Exception exception ) {
- if( exception == null )
- return null;
- if( exception is AspectCore.DynamicProxy.AspectInvocationException aspectInvocationException ) {
- if( aspectInvocationException.InnerException == null )
- return aspectInvocationException;
- return GetRawException( aspectInvocationException.InnerException );
- }
- return exception;
- }
-
- ///
- /// 获取异常提示
- ///
- /// 异常
- /// 是否生产环境
- public static string GetPrompt( this Exception exception, bool isProduction = false ) {
- if( exception == null )
- return null;
- exception = exception.GetRawException();
- if( exception == null )
- return null;
- if( exception is Warning warning )
- return warning.GetMessage( isProduction );
- return isProduction ? R.SystemError : exception.Message;
- }
-
- ///
- /// 获取Http状态码
- ///
- /// 异常
- public static int? GetHttpStatusCode( this Exception exception ) {
- if ( exception == null )
- return null;
- exception = exception.GetRawException();
- if ( exception == null )
- return null;
- if ( exception is Warning warning )
- return warning.HttpStatusCode;
- return null;
- }
-
- ///
- /// 获取错误码
- ///
- /// 异常
- public static string GetErrorCode( this Exception exception ) {
- if ( exception == null )
- return null;
- exception = exception.GetRawException();
- if ( exception == null )
- return null;
- if ( exception is Warning warning )
- return warning.Code;
- return null;
- }
+using Util.Exceptions;
+using Util.Properties;
+
+namespace Util.Applications;
+
+///
+/// 异常扩展
+///
+public static class ExceptionExtensions {
+ ///
+ /// 获取原始异常
+ ///
+ /// 异常
+ public static Exception GetRawException( this Exception exception ) {
+ if( exception == null )
+ return null;
+ if( exception is AspectCore.DynamicProxy.AspectInvocationException aspectInvocationException ) {
+ if( aspectInvocationException.InnerException == null )
+ return aspectInvocationException;
+ return GetRawException( aspectInvocationException.InnerException );
+ }
+ return exception;
+ }
+
+ ///
+ /// 获取异常提示
+ ///
+ /// 异常
+ /// 是否生产环境
+ public static string GetPrompt( this Exception exception, bool isProduction = false ) {
+ if( exception == null )
+ return null;
+ exception = exception.GetRawException();
+ if( exception == null )
+ return null;
+ if( exception is Warning warning )
+ return warning.GetMessage( isProduction );
+ return isProduction ? R.SystemError : exception.Message;
+ }
+
+ ///
+ /// 获取Http状态码
+ ///
+ /// 异常
+ public static int? GetHttpStatusCode( this Exception exception ) {
+ if ( exception == null )
+ return null;
+ exception = exception.GetRawException();
+ if ( exception == null )
+ return null;
+ if ( exception is Warning warning )
+ return warning.HttpStatusCode;
+ return null;
+ }
+
+ ///
+ /// 获取错误码
+ ///
+ /// 异常
+ public static string GetErrorCode( this Exception exception ) {
+ if ( exception == null )
+ return null;
+ exception = exception.GetRawException();
+ if ( exception == null )
+ return null;
+ if ( exception is Warning warning )
+ return warning.Code;
+ return null;
+ }
}
\ No newline at end of file
diff --git a/src/Util.Application/Usings.cs b/src/Util.Application/Usings.cs
index ef15a8d5c..03262834b 100644
--- a/src/Util.Application/Usings.cs
+++ b/src/Util.Application/Usings.cs
@@ -2,27 +2,8 @@
global using System.Threading.Tasks;
global using System.Collections.Generic;
global using System.Linq;
-global using System.Threading;
-global using System.Text;
-global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Microsoft.AspNetCore.Mvc;
global using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
\ No newline at end of file
diff --git a/src/Util.AspNetCore/07-Util.AspNetCore.csproj b/src/Util.AspNetCore/07-Util.AspNetCore.csproj
index 3a9baff9f..c5a2f42ea 100644
--- a/src/Util.AspNetCore/07-Util.AspNetCore.csproj
+++ b/src/Util.AspNetCore/07-Util.AspNetCore.csproj
@@ -18,12 +18,6 @@
.\obj\Release\$(NetTargetFramework)\Util.AspNetCore.xml
-
-
-
-
-
-
True
diff --git a/src/Util.AspNetCore/AspNetCore/IJsonSerializerOptionsFactory.cs b/src/Util.AspNetCore/AspNetCore/IJsonSerializerOptionsFactory.cs
new file mode 100644
index 000000000..0c5936878
--- /dev/null
+++ b/src/Util.AspNetCore/AspNetCore/IJsonSerializerOptionsFactory.cs
@@ -0,0 +1,13 @@
+using Util.Dependency;
+
+namespace Util.AspNetCore;
+
+///
+/// Json序列化配置工厂
+///
+public interface IJsonSerializerOptionsFactory : ISingletonDependency {
+ ///
+ /// 创建Json序列化配置
+ ///
+ JsonSerializerOptions CreateOptions();
+}
\ No newline at end of file
diff --git a/src/Util.AspNetCore/Http/HttpRequest.cs b/src/Util.AspNetCore/Http/HttpRequest.cs
index 65048d5f5..44045ebb4 100644
--- a/src/Util.AspNetCore/Http/HttpRequest.cs
+++ b/src/Util.AspNetCore/Http/HttpRequest.cs
@@ -1,4 +1,6 @@
-using Util.Helpers;
+using System.Text.Encodings.Web;
+using System.Text.Unicode;
+using Util.Helpers;
using Util.SystemTextJson;
namespace Util.Http;
@@ -67,6 +69,10 @@ public HttpRequest( IHttpClientFactory httpClientFactory, HttpClient httpClient,
#region 属性
+ ///
+ /// 基地址
+ ///
+ protected string BaseAddressUri { get; private set; }
///
/// 证书路径
///
@@ -116,6 +122,10 @@ public HttpRequest( IHttpClientFactory httpClientFactory, HttpClient httpClient,
///
protected Action SuccessAction { get; private set; }
///
+ /// 执行成功操作
+ ///
+ protected Func SuccessFunc { get; private set; }
+ ///
/// 执行失败操作
///
protected Action FailAction { get; private set; }
@@ -126,7 +136,7 @@ public HttpRequest( IHttpClientFactory httpClientFactory, HttpClient httpClient,
#endregion
- #region HttpClientName(Http客户端名称)
+ #region HttpClientName(设置Http客户端名称)
///
public IHttpRequest HttpClientName( string name ) {
@@ -136,6 +146,19 @@ public IHttpRequest HttpClientName( string name ) {
#endregion
+ #region BaseAddress(设置基地址)
+
+ ///
+ /// 设置基地址
+ ///
+ /// 基地址
+ public IHttpRequest BaseAddress( string baseAddress ) {
+ BaseAddressUri = baseAddress;
+ return this;
+ }
+
+ #endregion
+
#region ContentType(设置内容类型)
///
@@ -166,6 +189,16 @@ public IHttpRequest Encoding( Encoding encoding ) {
#endregion
+ #region BearerToken(设置访问令牌)
+
+ ///
+ public IHttpRequest BearerToken( string token ) {
+ Header( "Authorization", $"Bearer {token}" );
+ return this;
+ }
+
+ #endregion
+
#region Certificate(设置证书)
///
@@ -187,6 +220,28 @@ public IHttpRequest JsonSerializerOptions( JsonSerializerOptions option
#endregion
+ #region GetJsonSerializerOptions(获取Json序列化配置)
+
+ ///
+ /// 获取Json序列化配置
+ ///
+ protected virtual JsonSerializerOptions GetJsonSerializerOptions() {
+ if ( _jsonSerializerOptions != null )
+ return _jsonSerializerOptions;
+ return new JsonSerializerOptions {
+ PropertyNameCaseInsensitive = true,
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ NumberHandling = JsonNumberHandling.AllowReadingFromString,
+ Encoder = JavaScriptEncoder.Create( UnicodeRanges.All ),
+ Converters = {
+ new DateTimeJsonConverter(),
+ new NullableDateTimeJsonConverter()
+ }
+ };
+ }
+
+ #endregion
+
#region Header(设置请求头)
///
@@ -333,6 +388,15 @@ public IHttpRequest OnSuccess( Action action ) {
return this;
}
+ ///
+ /// 请求成功事件
+ ///
+ /// 执行成功操作,参数为响应结果
+ public IHttpRequest OnSuccess( Func action ) {
+ SuccessFunc = action;
+ return this;
+ }
+
#endregion
#region OnFail(请求失败事件)
@@ -358,11 +422,11 @@ public IHttpRequest OnComplete( Action act
#region GetResultAsync(获取结果)
///
- public async Task GetResultAsync() {
+ public async Task GetResultAsync( CancellationToken cancellationToken = default ) {
var message = CreateMessage();
if( SendBefore( message ) == false )
return default;
- var response = await SendAsync( message );
+ var response = await SendAsync( message, cancellationToken );
return await SendAfterAsync( response );
}
@@ -469,21 +533,6 @@ private string GetJsonContentValue() {
return null;
}
- ///
- /// 获取Json序列化配置
- ///
- protected virtual JsonSerializerOptions GetJsonSerializerOptions() {
- if ( _jsonSerializerOptions != null )
- return _jsonSerializerOptions;
- return new JsonSerializerOptions {
- DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
- Converters = {
- new DateTimeJsonConverter(),
- new NullableDateTimeJsonConverter()
- }
- };
- }
-
///
/// 创建xml内容
///
@@ -513,9 +562,12 @@ protected virtual bool SendBefore( HttpRequestMessage message ) {
/// 发送请求
///
/// 请求消息
- protected async Task SendAsync( HttpRequestMessage message ) {
+ /// 取消令牌
+ protected async Task SendAsync( HttpRequestMessage message, CancellationToken cancellationToken ) {
var client = GetClient();
- return await client.SendAsync( message );
+ client.CheckNull( nameof( client ) );
+ InitHttpClient( client );
+ return await client.SendAsync( message, cancellationToken );
}
#endregion
@@ -530,9 +582,7 @@ protected HttpClient GetClient() {
return _httpClient;
var clientHandler = CreateHttpClientHandler();
InitHttpClientHandler( clientHandler );
- if( _httpClientName.IsEmpty() )
- return _httpClientFactory.CreateClient();
- return _httpClientFactory.CreateClient( _httpClientName );
+ return _httpClientName.IsEmpty() ? _httpClientFactory.CreateClient() : _httpClientFactory.CreateClient( _httpClientName );
}
///
@@ -541,7 +591,7 @@ protected HttpClient GetClient() {
protected HttpClientHandler CreateHttpClientHandler() {
var handlerFactory = _httpClientFactory as IHttpMessageHandlerFactory;
var handler = handlerFactory?.CreateHandler();
- while( handler is DelegatingHandler delegatingHandler ) {
+ while ( handler is DelegatingHandler delegatingHandler ) {
handler = delegatingHandler.InnerHandler;
}
return handler as HttpClientHandler;
@@ -564,15 +614,40 @@ protected virtual void InitHttpClientHandler( HttpClientHandler handler ) {
///
/// 初始化证书
///
- protected void InitCertificate( HttpClientHandler handler ) {
+ protected virtual void InitCertificate( HttpClientHandler handler ) {
if( CertificatePath.IsEmpty() )
return;
var certificate = new X509Certificate2( CertificatePath, CertificatePassword, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet );
+ handler.ClientCertificates.Clear();
handler.ClientCertificates.Add( certificate );
}
#endregion
+ #region InitHttpClient(初始化Http客户端)
+
+ ///
+ /// 初始化Http客户端
+ ///
+ protected virtual void InitHttpClient( HttpClient client ) {
+ InitBaseAddress( client );
+ }
+
+ #endregion
+
+ #region InitBaseAddress(初始化基地址)
+
+ ///
+ /// 初始化基地址
+ ///
+ protected virtual void InitBaseAddress( HttpClient client ) {
+ if ( BaseAddressUri.IsEmpty() )
+ return;
+ client.BaseAddress = new Uri( BaseAddressUri );
+ }
+
+ #endregion
+
#region SendAfterAsync(发送后操作)
///
@@ -586,7 +661,7 @@ protected virtual async Task SendAfterAsync( HttpResponseMessage respon
try {
content = await response.Content.ReadAsStringAsync();
if( response.IsSuccessStatusCode )
- return SuccessHandler( response, content );
+ return await SuccessHandlerAsync( response, content );
FailHandler( response, content );
return null;
}
@@ -602,8 +677,11 @@ protected virtual async Task SendAfterAsync( HttpResponseMessage respon
///
/// 成功处理操作
///
- protected virtual TResult SuccessHandler( HttpResponseMessage response, string content ) {
- TResult result = ConvertTo( content, response.GetContentType() );
+ protected virtual async Task SuccessHandlerAsync( HttpResponseMessage response, string content ) {
+ var result = ConvertTo( content, response.GetContentType() );
+ SuccessAction?.Invoke( result );
+ if ( SuccessFunc != null )
+ await SuccessFunc( result );
return result;
}
@@ -621,17 +699,7 @@ protected virtual TResult ConvertTo( string content, string contentType ) {
return ConvertAction( content );
if( typeof( TResult ) == typeof( string ) )
return (TResult)(object)content;
- if( contentType.SafeString().ToLower() == "application/json" ) {
- var options = new JsonSerializerOptions {
- PropertyNameCaseInsensitive = true,
- Converters = {
- new DateTimeJsonConverter(),
- new NullableDateTimeJsonConverter()
- }
- };
- return Json.ToObject( content, options );
- }
- return null;
+ return contentType.SafeString().ToLower() == "application/json" ? Json.ToObject( content, GetJsonSerializerOptions() ) : null;
}
#endregion
@@ -661,11 +729,11 @@ protected virtual void CompleteHandler( HttpResponseMessage response, object con
#region GetStreamAsync(获取流)
///
- public async Task GetStreamAsync() {
+ public async Task GetStreamAsync( CancellationToken cancellationToken = default ) {
var message = CreateMessage();
if( SendBefore( message ) == false )
return default;
- var response = await SendAsync( message );
+ var response = await SendAsync( message, cancellationToken );
return await GetStream( response );
}
@@ -692,8 +760,8 @@ protected virtual async Task GetStream( HttpResponseMessage response ) {
#region WriteAsync(写入文件)
///
- public async Task WriteAsync( string filePath ) {
- var bytes = await GetStreamAsync();
+ public async Task WriteAsync( string filePath, CancellationToken cancellationToken = default ) {
+ var bytes = await GetStreamAsync( cancellationToken );
await Util.Helpers.File.WriteAsync( filePath, bytes );
}
diff --git a/src/Util.AspNetCore/Usings.cs b/src/Util.AspNetCore/Usings.cs
index c7f913425..4ccdbdcc0 100644
--- a/src/Util.AspNetCore/Usings.cs
+++ b/src/Util.AspNetCore/Usings.cs
@@ -3,24 +3,11 @@
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
-global using System.Diagnostics;
global using System.Text;
global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
global using System.Globalization;
global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Security.Cryptography;
-global using System.Security.Principal;
global using System.Net.NetworkInformation;
global using System.Net.Sockets;
global using System.Net;
@@ -30,11 +17,7 @@
global using Microsoft.AspNetCore.Hosting;
global using Microsoft.AspNetCore.Http;
global using Microsoft.AspNetCore.Http.Extensions;
-global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Microsoft.AspNetCore.WebUtilities;
global using Microsoft.AspNetCore.Authorization;
diff --git a/src/Util.Caching.EasyCaching/Usings.cs b/src/Util.Caching.EasyCaching/Usings.cs
index fb2d33ac0..ef479070b 100644
--- a/src/Util.Caching.EasyCaching/Usings.cs
+++ b/src/Util.Caching.EasyCaching/Usings.cs
@@ -3,27 +3,10 @@
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
global using Microsoft.Extensions.DependencyInjection.Extensions;
global using EasyCaching.Core;
global using EasyCaching.Core.Interceptor;
diff --git a/src/Util.Caching/Usings.cs b/src/Util.Caching/Usings.cs
index e5f9b8dc5..4c6502951 100644
--- a/src/Util.Caching/Usings.cs
+++ b/src/Util.Caching/Usings.cs
@@ -3,26 +3,6 @@
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using AspectCore.DynamicProxy;
\ No newline at end of file
diff --git a/src/Util.Core/Exceptions/Warning.cs b/src/Util.Core/Exceptions/Warning.cs
index 0582a5346..a3d90b6c6 100644
--- a/src/Util.Core/Exceptions/Warning.cs
+++ b/src/Util.Core/Exceptions/Warning.cs
@@ -16,8 +16,8 @@ public Warning( Exception exception )
/// 初始化应用程序异常
///
/// 错误消息
- /// 错误码
/// 异常
+ /// 错误码
/// Http状态码
public Warning( string message, Exception exception = null, string code = null, int? httpStatusCode = null )
: base( message ?? "", exception ) {
diff --git a/src/Util.Core/Helpers/Common.cs b/src/Util.Core/Helpers/Common.cs
index 8ca2246dd..9f52cdb9a 100644
--- a/src/Util.Core/Helpers/Common.cs
+++ b/src/Util.Core/Helpers/Common.cs
@@ -71,7 +71,14 @@ public static string GetCurrentDirectory() {
///
/// 获取当前目录的上级路径
///
- public static string GetParentDirectory() {
- return Directory.GetParent( Directory.GetCurrentDirectory() )?.FullName;
+ /// 向上钻取的深度
+ public static string GetParentDirectory( int depth = 1 ) {
+ var path = Directory.GetCurrentDirectory();
+ for ( int i = 0; i < depth; i++ ) {
+ var parent = Directory.GetParent( path );
+ if ( parent is { Exists: true } )
+ path = parent.FullName;
+ }
+ return path;
}
}
\ No newline at end of file
diff --git a/src/Util.Core/Helpers/Config.cs b/src/Util.Core/Helpers/Config.cs
index ec867fa7c..26ea7278b 100644
--- a/src/Util.Core/Helpers/Config.cs
+++ b/src/Util.Core/Helpers/Config.cs
@@ -66,14 +66,14 @@ public static IConfiguration CreateConfiguration( string basePath = null,params
basePath ??= Common.ApplicationBaseDirectory;
var builder = new ConfigurationBuilder()
.SetBasePath( basePath )
- .AddJsonFile( "appsettings.json", true, true );
+ .AddJsonFile( "appsettings.json", true, false );
var environment = Environment.GetEnvironmentName();
if ( environment.IsEmpty() == false )
- builder.AddJsonFile( $"appsettings.{environment}.json", true, true );
+ builder.AddJsonFile( $"appsettings.{environment}.json", true, false );
if ( jsonFiles == null )
return builder.Build();
foreach ( var file in jsonFiles )
- builder.AddJsonFile( file, true, true );
+ builder.AddJsonFile( file, true, false );
return builder.Build();
}
diff --git a/src/Util.Core/Helpers/Convert.cs b/src/Util.Core/Helpers/Convert.cs
index 978408fa5..37ce66630 100644
--- a/src/Util.Core/Helpers/Convert.cs
+++ b/src/Util.Core/Helpers/Convert.cs
@@ -313,7 +313,7 @@ public static T To( object input ) {
return default;
if( input is string && string.IsNullOrWhiteSpace( input.ToString() ) )
return default;
- Type type = Common.GetType();
+ var type = Common.GetType();
var typeName = type.Name.ToUpperInvariant();
try {
if( typeName == "STRING" || typeName == "GUID" )
@@ -342,11 +342,11 @@ public static T To( object input ) {
///
/// 对象
public static IDictionary ToDictionary( object data ) {
- if( data == null )
- return null;
+ var result = new Dictionary();
+ if ( data == null )
+ return result;
if ( data is IEnumerable> dic )
return new Dictionary( dic );
- var result = new Dictionary();
foreach ( PropertyDescriptor property in TypeDescriptor.GetProperties( data ) ) {
var value = property.GetValue( data );
result.Add( property.Name, value );
diff --git a/src/Util.Core/Helpers/Json.cs b/src/Util.Core/Helpers/Json.cs
index dbc23e08f..50e51df9c 100644
--- a/src/Util.Core/Helpers/Json.cs
+++ b/src/Util.Core/Helpers/Json.cs
@@ -12,11 +12,22 @@ public static class Json {
/// 目标对象
/// Json配置
public static string ToJson( T value, JsonOptions options ) {
- options ??= new JsonOptions();
+ if ( options == null )
+ return ToJson( value );
+ var jsonSerializerOptions = ToJsonSerializerOptions( options );
+ return ToJson( value, jsonSerializerOptions, options.RemoveQuotationMarks, options.ToSingleQuotes, options.IgnoreInterface );
+ }
+
+ ///
+ /// 转换序列化配置
+ ///
+ private static JsonSerializerOptions ToJsonSerializerOptions( JsonOptions options ) {
var jsonSerializerOptions = new JsonSerializerOptions();
if ( options.IgnoreNullValues )
jsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
- return ToJson( value, jsonSerializerOptions, options.RemoveQuotationMarks, options.ToSingleQuotes );
+ if ( options.IgnoreCase )
+ jsonSerializerOptions.PropertyNameCaseInsensitive = true;
+ return jsonSerializerOptions;
}
///
@@ -27,12 +38,19 @@ public static string ToJson( T value, JsonOptions options ) {
/// 是否移除双引号
/// 是否将双引号转成单引号
public static string ToJson( T value, JsonSerializerOptions options = null,bool removeQuotationMarks = false, bool toSingleQuotes = false ) {
+ return ToJson( value, options, removeQuotationMarks, toSingleQuotes,true );
+ }
+
+ ///
+ /// 将对象转换为Json字符串
+ ///
+ private static string ToJson( T value, JsonSerializerOptions options, bool removeQuotationMarks, bool toSingleQuotes,bool ignoreInterface ) {
if ( value == null )
return string.Empty;
options = GetToJsonOptions( options );
- var result = JsonSerializer.Serialize( value, options );
+ var result = Serialize( value, options, ignoreInterface );
if ( removeQuotationMarks )
- result = result.Replace( "\"","" );
+ result = result.Replace( "\"", "" );
if ( toSingleQuotes )
result = result.Replace( "\"", "'" );
return result;
@@ -53,6 +71,18 @@ private static JsonSerializerOptions GetToJsonOptions( JsonSerializerOptions opt
};
}
+ ///
+ /// Json序列化
+ ///
+ private static string Serialize( T value, JsonSerializerOptions options, bool ignoreInterface ) {
+ if ( ignoreInterface ) {
+ object instance = value;
+ if( instance != null )
+ return JsonSerializer.Serialize( instance, options );
+ }
+ return JsonSerializer.Serialize( value, options );
+ }
+
///
/// 将对象转换为Json字符串
///
@@ -70,6 +100,19 @@ private static JsonSerializerOptions GetToJsonOptions( JsonSerializerOptions opt
return await reader.ReadToEndAsync( cancellationToken );
}
+ ///
+ /// 将Json字符串转换为对象
+ ///
+ /// Json字符串
+ /// 序列化配置
+ public static T ToObject( string json, JsonOptions options ) {
+ if ( string.IsNullOrWhiteSpace( json ) )
+ return default;
+ if ( options == null )
+ return ToObject( json );
+ return ToObject( json, ToJsonSerializerOptions( options ) );
+ }
+
///
/// 将Json字符串转换为对象
///
@@ -117,9 +160,9 @@ private static JsonSerializerOptions GetToObjectOptions( JsonSerializerOptions o
///
/// Json字符串
/// 序列化配置
- /// 取消令牌
/// Json字符编码,默认UTF8
- public static async Task ToObjectAsync( string json, JsonSerializerOptions options = null, CancellationToken cancellationToken = default,Encoding encoding = null ) {
+ /// 取消令牌
+ public static async Task ToObjectAsync( string json, JsonSerializerOptions options = null, Encoding encoding = null, CancellationToken cancellationToken = default ) {
if ( string.IsNullOrWhiteSpace( json ) )
return default;
encoding ??= Encoding.UTF8;
diff --git a/src/Util.Core/Helpers/Xml.Builder.cs b/src/Util.Core/Helpers/Xml.Builder.cs
new file mode 100644
index 000000000..2f2308630
--- /dev/null
+++ b/src/Util.Core/Helpers/Xml.Builder.cs
@@ -0,0 +1,95 @@
+namespace Util.Helpers;
+
+///
+/// Xml操作 - 生成器
+///
+public partial class Xml {
+ ///
+ /// 初始化Xml操作
+ ///
+ /// Xml字符串
+ public Xml( string xml = null ) {
+ Document = new XmlDocument();
+ Document.LoadXml( GetXml( xml ) );
+ Root = Document.DocumentElement;
+ if( Root == null )
+ throw new ArgumentException( nameof( xml ) );
+ }
+
+ ///
+ /// 获取Xml字符串
+ ///
+ private string GetXml( string xml ) {
+ return string.IsNullOrWhiteSpace( xml ) ? "" : xml;
+ }
+
+ ///
+ /// Xml文档
+ ///
+ public XmlDocument Document { get; }
+
+ ///
+ /// Xml根节点
+ ///
+ public XmlElement Root { get; }
+
+ ///
+ /// 添加节点
+ ///
+ /// 节点名称
+ /// 值
+ /// 父节点
+ public XmlNode AddNode( string name, object value = null, XmlNode parent = null ) {
+ var node = CreateNode( name, value, XmlNodeType.Element );
+ GetParent( parent ).AppendChild( node );
+ return node;
+ }
+
+ ///
+ /// 创建节点
+ ///
+ private XmlNode CreateNode( string name, object value, XmlNodeType type ) {
+ var node = Document.CreateNode( type, name, string.Empty );
+ if( string.IsNullOrWhiteSpace( value.SafeString() ) == false )
+ node.InnerText = value.SafeString();
+ return node;
+ }
+
+ ///
+ /// 获取父节点
+ ///
+ private XmlNode GetParent( XmlNode parent ) {
+ if( parent == null )
+ return Root;
+ return parent;
+ }
+
+ ///
+ /// 添加CDATA节点
+ ///
+ /// 值
+ /// 父节点
+ public XmlNode AddCDataNode( object value, XmlNode parent = null ) {
+ var node = CreateNode( Id.Create(), value, XmlNodeType.CDATA );
+ GetParent( parent ).AppendChild( node );
+ return node;
+ }
+
+ ///
+ /// 添加CDATA节点
+ ///
+ /// 值
+ /// 父节点名称
+ public XmlNode AddCDataNode( object value, string parentName ) {
+ var parent = CreateNode( parentName, null, XmlNodeType.Element );
+ Root.AppendChild( parent );
+ return AddCDataNode( value, parent );
+ }
+
+ ///
+ /// 输出Xml
+ ///
+ public override string ToString() {
+ return Document.OuterXml;
+ }
+}
\ No newline at end of file
diff --git a/src/Util.Core/Helpers/Xml.Tools.cs b/src/Util.Core/Helpers/Xml.Tools.cs
new file mode 100644
index 000000000..7bc9e9247
--- /dev/null
+++ b/src/Util.Core/Helpers/Xml.Tools.cs
@@ -0,0 +1,61 @@
+namespace Util.Helpers;
+
+///
+/// Xml操作 - 工具
+///
+public partial class Xml {
+ ///
+ /// 将Xml字符串转换为XDocument
+ ///
+ /// Xml字符串
+ public static XDocument ToDocument( string xml ) {
+ return XDocument.Parse( xml );
+ }
+
+ ///
+ /// 将Xml字符串转换为XElement列表
+ ///
+ /// Xml字符串
+ public static List ToElements( string xml ) {
+ var document = ToDocument( xml );
+ if( document?.Root == null )
+ return new List();
+ return document.Root.Elements().ToList();
+ }
+
+ ///
+ /// 加载Xml文件到XDocument
+ ///
+ /// Xml文件绝对路径
+ public static async Task LoadFileToDocumentAsync( string filePath ) {
+ return await LoadFileToDocumentAsync( filePath, Encoding.UTF8 );
+ }
+
+ ///
+ /// 加载Xml文件到XDocument
+ ///
+ /// Xml文件绝对路径
+ /// 字符编码
+ public static async Task LoadFileToDocumentAsync( string filePath,Encoding encoding ) {
+ var xml = await Util.Helpers.File.ReadToStringAsync( filePath, encoding );
+ return ToDocument( xml );
+ }
+
+ ///
+ /// 加载Xml文件到XElement列表
+ ///
+ /// Xml文件绝对路径
+ public static async Task> LoadFileToElementsAsync( string filePath ) {
+ return await LoadFileToElementsAsync( filePath, Encoding.UTF8 );
+ }
+
+ ///
+ /// 加载Xml文件到XElement列表
+ ///
+ /// Xml文件绝对路径
+ /// 字符编码
+ public static async Task> LoadFileToElementsAsync( string filePath, Encoding encoding ) {
+ var xml = await Util.Helpers.File.ReadToStringAsync( filePath, encoding );
+ return ToElements( xml );
+ }
+}
\ No newline at end of file
diff --git a/src/Util.Core/Http/IHttpRequest.cs b/src/Util.Core/Http/IHttpRequest.cs
index 1a2b2e5f7..563ed7343 100644
--- a/src/Util.Core/Http/IHttpRequest.cs
+++ b/src/Util.Core/Http/IHttpRequest.cs
@@ -17,6 +17,11 @@ public interface IHttpRequest : IHttpRequest where TResult : class {
/// HttpClient名称
IHttpRequest HttpClientName( string name );
///
+ /// 设置基地址
+ ///
+ /// 基地址
+ IHttpRequest BaseAddress( string baseAddress );
+ ///
/// 设置字符编码
///
/// 字符编码,范例:gb2312
@@ -27,6 +32,11 @@ public interface IHttpRequest : IHttpRequest where TResult : class {
/// 字符编码
IHttpRequest Encoding( Encoding encoding );
///
+ /// 设置访问令牌
+ ///
+ /// 访问令牌
+ IHttpRequest BearerToken( string token );
+ ///
/// 设置内容类型
///
/// 内容类型
@@ -121,6 +131,11 @@ public interface IHttpRequest : IHttpRequest where TResult : class {
/// 执行成功操作,参数为响应结果
IHttpRequest OnSuccess( Action action );
///
+ /// 请求成功事件
+ ///
+ /// 执行成功操作,参数为响应结果
+ IHttpRequest OnSuccess( Func action );
+ ///
/// 请求失败事件
///
/// 执行失败操作,参数为响应消息和响应内容
@@ -133,14 +148,17 @@ public interface IHttpRequest : IHttpRequest where TResult : class {
///
/// 获取结果
///
- Task GetResultAsync();
+ /// 取消令牌
+ Task GetResultAsync( CancellationToken cancellationToken = default );
///
/// 获取流
///
- Task GetStreamAsync();
+ /// 取消令牌
+ Task GetStreamAsync( CancellationToken cancellationToken = default );
///
/// 写入文件
///
/// 文件绝对路径
- Task WriteAsync( string filePath );
+ /// 取消令牌
+ Task WriteAsync( string filePath, CancellationToken cancellationToken = default );
}
\ No newline at end of file
diff --git a/src/Util.Core/JsonOptions.cs b/src/Util.Core/JsonOptions.cs
index c7ca8f5bb..2eeadc61a 100644
--- a/src/Util.Core/JsonOptions.cs
+++ b/src/Util.Core/JsonOptions.cs
@@ -4,6 +4,15 @@
/// Json配置
///
public class JsonOptions {
+ ///
+ /// 初始化Json配置
+ ///
+ public JsonOptions() {
+ IgnoreNullValues = true;
+ IgnoreCase = true;
+ IgnoreInterface = true;
+ }
+
///
/// 是否移除双引号,默认值: false
///
@@ -13,7 +22,15 @@ public class JsonOptions {
///
public bool ToSingleQuotes { get; set; }
///
- /// 是否忽略null值,默认值: false
+ /// 是否忽略null值,默认值: true
///
public bool IgnoreNullValues { get; set; }
+ ///
+ /// 反序列化时是否忽略大小写,默认值: true
+ ///
+ public bool IgnoreCase { get; set; }
+ ///
+ /// 反序列化接口实例时是否忽略接口,按实现类进行序列化,默认值: true
+ ///
+ public bool IgnoreInterface { get; set; }
}
\ No newline at end of file
diff --git a/src/Util.Core/Properties/R.Designer.cs b/src/Util.Core/Properties/R.Designer.cs
index 7d6fe3daf..215fd508e 100644
--- a/src/Util.Core/Properties/R.Designer.cs
+++ b/src/Util.Core/Properties/R.Designer.cs
@@ -231,6 +231,15 @@ public static string TypeNotEnum {
}
}
+ ///
+ /// 查找类似 您没有该操作的权限 的本地化字符串。
+ ///
+ public static string UnauthorizedMessage {
+ get {
+ return ResourceManager.GetString("UnauthorizedMessage", resourceCulture);
+ }
+ }
+
///
/// 查找类似 上传 的本地化字符串。
///
diff --git a/src/Util.Core/Properties/R.resx b/src/Util.Core/Properties/R.resx
index 5527b167e..e584c26a8 100644
--- a/src/Util.Core/Properties/R.resx
+++ b/src/Util.Core/Properties/R.resx
@@ -175,6 +175,9 @@
类型 {0} 不是枚举
+
+ 您没有该操作的权限
+
上传
diff --git a/src/Util.Core/Usings.cs b/src/Util.Core/Usings.cs
index 536708a62..689e28fa2 100644
--- a/src/Util.Core/Usings.cs
+++ b/src/Util.Core/Usings.cs
@@ -19,8 +19,9 @@
global using System.Text.Unicode;
global using System.Buffers;
global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
global using System.Net.Http;
+global using System.Xml;
+global using System.Xml.Linq;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
diff --git a/src/Util.Core/ValidationExtensions.cs b/src/Util.Core/ValidationExtensions.cs
index 7802d04f2..fc0a48baa 100644
--- a/src/Util.Core/ValidationExtensions.cs
+++ b/src/Util.Core/ValidationExtensions.cs
@@ -1,4 +1,5 @@
-namespace Util;
+#nullable enable
+namespace Util;
///
/// 验证扩展
@@ -44,7 +45,7 @@ public static bool IsEmpty( [NotNullWhen( false )] this Guid? value ) {
/// 是否为空
///
/// 值
- public static bool IsEmpty( this IEnumerable value ) {
+ public static bool IsEmpty( this IEnumerable? value ) {
if( value == null )
return true;
return !value.Any();
diff --git a/src/Util.Data.Abstractions/Usings.cs b/src/Util.Data.Abstractions/Usings.cs
index 82845070f..6eb207db5 100644
--- a/src/Util.Data.Abstractions/Usings.cs
+++ b/src/Util.Data.Abstractions/Usings.cs
@@ -3,28 +3,4 @@
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Security.Cryptography;
-global using System.Security.Claims;
-global using System.Security.Principal;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
\ No newline at end of file
+global using System.Linq.Expressions;
\ No newline at end of file
diff --git a/src/Util.Data.Core/Usings.cs b/src/Util.Data.Core/Usings.cs
index 05071e106..5ad6166fa 100644
--- a/src/Util.Data.Core/Usings.cs
+++ b/src/Util.Data.Core/Usings.cs
@@ -2,29 +2,7 @@
global using System.Threading.Tasks;
global using System.Collections.Generic;
global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
global using System.Data;
global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
\ No newline at end of file
diff --git a/src/Util.Data.Dapper.All/Usings.cs b/src/Util.Data.Dapper.All/Usings.cs
index eff011f74..3e51ec473 100644
--- a/src/Util.Data.Dapper.All/Usings.cs
+++ b/src/Util.Data.Dapper.All/Usings.cs
@@ -1,31 +1,2 @@
global using System;
-global using System.Threading.Tasks;
-global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Data;
-global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
global using Microsoft.Extensions.DependencyInjection.Extensions;
-global using Dapper;
diff --git a/src/Util.Data.Dapper.Core/Usings.cs b/src/Util.Data.Dapper.Core/Usings.cs
index eff011f74..14a52a9ff 100644
--- a/src/Util.Data.Dapper.Core/Usings.cs
+++ b/src/Util.Data.Dapper.Core/Usings.cs
@@ -2,30 +2,13 @@
global using System.Threading.Tasks;
global using System.Collections.Generic;
global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
global using System.Text;
-global using System.IO;
global using System.Data;
-global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
global using System.Text.Encodings.Web;
global using System.Text.Json.Serialization;
global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Dapper;
diff --git a/src/Util.Data.Dapper.MySql/Usings.cs b/src/Util.Data.Dapper.MySql/Usings.cs
index 14f159f4c..75d67f651 100644
--- a/src/Util.Data.Dapper.MySql/Usings.cs
+++ b/src/Util.Data.Dapper.MySql/Usings.cs
@@ -2,31 +2,8 @@
global using System.Threading.Tasks;
global using System.Collections.Generic;
global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
global using System.Text;
-global using System.IO;
global using System.Data;
-global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
global using Microsoft.Extensions.DependencyInjection.Extensions;
-global using Dapper;
global using MySqlConnector;
diff --git a/src/Util.Data.Dapper.PostgreSql/Usings.cs b/src/Util.Data.Dapper.PostgreSql/Usings.cs
index 46153acee..6d83fa6b9 100644
--- a/src/Util.Data.Dapper.PostgreSql/Usings.cs
+++ b/src/Util.Data.Dapper.PostgreSql/Usings.cs
@@ -2,31 +2,8 @@
global using System.Threading.Tasks;
global using System.Collections.Generic;
global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
global using System.Text;
-global using System.IO;
global using System.Data;
-global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
global using Microsoft.Extensions.DependencyInjection.Extensions;
-global using Dapper;
global using Npgsql;
diff --git a/src/Util.Data.Dapper.SqlServer/Usings.cs b/src/Util.Data.Dapper.SqlServer/Usings.cs
index 995f832bb..68c543f15 100644
--- a/src/Util.Data.Dapper.SqlServer/Usings.cs
+++ b/src/Util.Data.Dapper.SqlServer/Usings.cs
@@ -2,31 +2,8 @@
global using System.Threading.Tasks;
global using System.Collections.Generic;
global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
global using System.Text;
-global using System.IO;
global using System.Data;
-global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Microsoft.Data.SqlClient;
-global using Dapper;
diff --git a/src/Util.Data.EntityFrameworkCore.MySql/Usings.cs b/src/Util.Data.EntityFrameworkCore.MySql/Usings.cs
index 4be7c681d..4a26a3949 100644
--- a/src/Util.Data.EntityFrameworkCore.MySql/Usings.cs
+++ b/src/Util.Data.EntityFrameworkCore.MySql/Usings.cs
@@ -1,39 +1,6 @@
global using System;
-global using System.Threading.Tasks;
-global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Data;
-global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
global using System.Data.Common;
-global using System.Buffers;
-global using System.Collections;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using System.ComponentModel.DataAnnotations.Schema;
-global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Microsoft.EntityFrameworkCore;
-global using Microsoft.EntityFrameworkCore.ChangeTracking;
-global using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
-global using Microsoft.EntityFrameworkCore.Metadata;
global using Microsoft.EntityFrameworkCore.Infrastructure;
global using MySqlConnector;
diff --git a/src/Util.Data.EntityFrameworkCore.Oracle/Usings.cs b/src/Util.Data.EntityFrameworkCore.Oracle/Usings.cs
index 7d294fc60..797d4972e 100644
--- a/src/Util.Data.EntityFrameworkCore.Oracle/Usings.cs
+++ b/src/Util.Data.EntityFrameworkCore.Oracle/Usings.cs
@@ -1,39 +1,6 @@
global using System;
-global using System.Threading.Tasks;
-global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Data;
-global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
global using System.Data.Common;
-global using System.Buffers;
-global using System.Collections;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using System.ComponentModel.DataAnnotations.Schema;
-global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Microsoft.EntityFrameworkCore;
-global using Microsoft.EntityFrameworkCore.ChangeTracking;
-global using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
global using Microsoft.EntityFrameworkCore.Metadata;
-global using Microsoft.EntityFrameworkCore.Infrastructure;
global using Oracle.EntityFrameworkCore.Infrastructure;
\ No newline at end of file
diff --git a/src/Util.Data.EntityFrameworkCore.PostgreSql/Usings.cs b/src/Util.Data.EntityFrameworkCore.PostgreSql/Usings.cs
index ed2a33657..80c67f2ec 100644
--- a/src/Util.Data.EntityFrameworkCore.PostgreSql/Usings.cs
+++ b/src/Util.Data.EntityFrameworkCore.PostgreSql/Usings.cs
@@ -1,39 +1,5 @@
global using System;
-global using System.Threading.Tasks;
-global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Data;
-global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
global using System.Data.Common;
-global using System.Buffers;
-global using System.Collections;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using System.ComponentModel.DataAnnotations.Schema;
-global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Microsoft.EntityFrameworkCore;
-global using Microsoft.EntityFrameworkCore.ChangeTracking;
-global using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
-global using Microsoft.EntityFrameworkCore.Metadata;
-global using Microsoft.EntityFrameworkCore.Infrastructure;
global using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure;
\ No newline at end of file
diff --git a/src/Util.Data.EntityFrameworkCore.SqlServer/02-Util.Data.EntityFrameworkCore.SqlServer.csproj b/src/Util.Data.EntityFrameworkCore.SqlServer/02-Util.Data.EntityFrameworkCore.SqlServer.csproj
index fb46520e6..28b2c350e 100644
--- a/src/Util.Data.EntityFrameworkCore.SqlServer/02-Util.Data.EntityFrameworkCore.SqlServer.csproj
+++ b/src/Util.Data.EntityFrameworkCore.SqlServer/02-Util.Data.EntityFrameworkCore.SqlServer.csproj
@@ -27,7 +27,7 @@
-
+
diff --git a/src/Util.Data.EntityFrameworkCore.SqlServer/Usings.cs b/src/Util.Data.EntityFrameworkCore.SqlServer/Usings.cs
index 8bbcd04d1..343815cfa 100644
--- a/src/Util.Data.EntityFrameworkCore.SqlServer/Usings.cs
+++ b/src/Util.Data.EntityFrameworkCore.SqlServer/Usings.cs
@@ -1,38 +1,6 @@
global using System;
-global using System.Threading.Tasks;
-global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Data;
-global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
global using System.Data.Common;
-global using System.Buffers;
-global using System.Collections;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using System.ComponentModel.DataAnnotations.Schema;
-global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Microsoft.EntityFrameworkCore;
-global using Microsoft.EntityFrameworkCore.ChangeTracking;
-global using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
global using Microsoft.EntityFrameworkCore.Metadata;
global using Microsoft.EntityFrameworkCore.Infrastructure;
\ No newline at end of file
diff --git a/src/Util.Data.EntityFrameworkCore.Sqlite/05-Util.Data.EntityFrameworkCore.Sqlite.csproj b/src/Util.Data.EntityFrameworkCore.Sqlite/05-Util.Data.EntityFrameworkCore.Sqlite.csproj
index 994088f95..611f30679 100644
--- a/src/Util.Data.EntityFrameworkCore.Sqlite/05-Util.Data.EntityFrameworkCore.Sqlite.csproj
+++ b/src/Util.Data.EntityFrameworkCore.Sqlite/05-Util.Data.EntityFrameworkCore.Sqlite.csproj
@@ -27,7 +27,7 @@
-
+
diff --git a/src/Util.Data.EntityFrameworkCore.Sqlite/Usings.cs b/src/Util.Data.EntityFrameworkCore.Sqlite/Usings.cs
index 8bbcd04d1..731033ee7 100644
--- a/src/Util.Data.EntityFrameworkCore.Sqlite/Usings.cs
+++ b/src/Util.Data.EntityFrameworkCore.Sqlite/Usings.cs
@@ -1,38 +1,5 @@
global using System;
-global using System.Threading.Tasks;
-global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Data;
-global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
global using System.Data.Common;
-global using System.Buffers;
-global using System.Collections;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using System.ComponentModel.DataAnnotations.Schema;
-global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Microsoft.EntityFrameworkCore;
-global using Microsoft.EntityFrameworkCore.ChangeTracking;
-global using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
-global using Microsoft.EntityFrameworkCore.Metadata;
global using Microsoft.EntityFrameworkCore.Infrastructure;
\ No newline at end of file
diff --git a/src/Util.Data.EntityFrameworkCore/01-Util.Data.EntityFrameworkCore.csproj b/src/Util.Data.EntityFrameworkCore/01-Util.Data.EntityFrameworkCore.csproj
index 9174285da..c152a9ece 100644
--- a/src/Util.Data.EntityFrameworkCore/01-Util.Data.EntityFrameworkCore.csproj
+++ b/src/Util.Data.EntityFrameworkCore/01-Util.Data.EntityFrameworkCore.csproj
@@ -27,8 +27,8 @@
-
-
+
+
diff --git a/src/Util.Data.EntityFrameworkCore/UnitOfWorkBase.cs b/src/Util.Data.EntityFrameworkCore/UnitOfWorkBase.cs
index 825033d0f..d86f97033 100644
--- a/src/Util.Data.EntityFrameworkCore/UnitOfWorkBase.cs
+++ b/src/Util.Data.EntityFrameworkCore/UnitOfWorkBase.cs
@@ -538,32 +538,32 @@ protected virtual void AddEntityDeletedEvent( object entity ) {
/// 保存后操作
///
protected virtual async Task SaveChangesAfter() {
- await PublishEventsAsync();
await ExecuteActionsAsync();
+ await PublishEventsAsync();
}
#endregion
- #region PublishEventsAsync(发布事件)
+ #region ExecuteActionsAsync(执行工作单元操作集合)
///
- /// 发布事件
+ /// 执行工作单元操作集合
///
- protected virtual async Task PublishEventsAsync() {
- var events = new List( Events );
- Events.Clear();
- await EventBus.PublishAsync( events );
+ protected virtual async Task ExecuteActionsAsync() {
+ await ActionManager.ExecuteAsync();
}
#endregion
- #region ExecuteActionsAsync(执行工作单元操作集合)
+ #region PublishEventsAsync(发布事件)
///
- /// 执行工作单元操作集合
+ /// 发布事件
///
- protected virtual async Task ExecuteActionsAsync() {
- await ActionManager.ExecuteAsync();
+ protected virtual async Task PublishEventsAsync() {
+ var events = new List( Events );
+ Events.Clear();
+ await EventBus.PublishAsync( events );
}
#endregion
diff --git a/src/Util.Data.EntityFrameworkCore/UnitOfWorkExtensions.cs b/src/Util.Data.EntityFrameworkCore/UnitOfWorkExtensions.cs
index 67a32835b..c87450ad7 100644
--- a/src/Util.Data.EntityFrameworkCore/UnitOfWorkExtensions.cs
+++ b/src/Util.Data.EntityFrameworkCore/UnitOfWorkExtensions.cs
@@ -10,7 +10,7 @@ public static class UnitOfWorkExtensions {
/// 工作单元
public static async Task> GetAppliedMigrationsAsync( this IUnitOfWork source ) {
source.CheckNull( nameof( source ) );
- if ( source is not UnitOfWorkBase unitOfWork )
+ if ( source is not DbContext unitOfWork )
return new List();
var result = await unitOfWork.Database.GetAppliedMigrationsAsync();
return result.ToList();
@@ -23,7 +23,7 @@ public static async Task> GetAppliedMigrationsAsync( this IUnitOfWo
/// 取消令牌
public static async Task MigrateAsync( this IUnitOfWork source, CancellationToken cancellationToken = default ) {
source.CheckNull( nameof( source ) );
- if ( source is not UnitOfWorkBase unitOfWork )
+ if ( source is not DbContext unitOfWork )
return;
await unitOfWork.Database.MigrateAsync( cancellationToken );
}
@@ -34,7 +34,7 @@ public static async Task> GetAppliedMigrationsAsync( this IUnitOfWo
/// 工作单元
public static bool EnsureCreated( this IUnitOfWork source ) {
source.CheckNull( nameof( source ) );
- if( source is not UnitOfWorkBase unitOfWork )
+ if( source is not DbContext unitOfWork )
return false;
return unitOfWork.Database.EnsureCreated();
}
@@ -45,7 +45,7 @@ public static bool EnsureCreated( this IUnitOfWork source ) {
/// 工作单元
public static async Task EnsureCreatedAsync( this IUnitOfWork source ) {
source.CheckNull( nameof( source ) );
- if( source is not UnitOfWorkBase unitOfWork )
+ if( source is not DbContext unitOfWork )
return false;
return await unitOfWork.Database.EnsureCreatedAsync();
}
@@ -56,7 +56,7 @@ public static async Task EnsureCreatedAsync( this IUnitOfWork source ) {
/// 工作单元
public static bool EnsureDeleted( this IUnitOfWork source ) {
source.CheckNull( nameof( source ) );
- if( source is not UnitOfWorkBase unitOfWork )
+ if( source is not DbContext unitOfWork )
return false;
return unitOfWork.Database.EnsureDeleted();
}
@@ -67,7 +67,7 @@ public static bool EnsureDeleted( this IUnitOfWork source ) {
/// 工作单元
public static async Task EnsureDeletedAsync( this IUnitOfWork source ) {
source.CheckNull( nameof( source ) );
- if( source is not UnitOfWorkBase unitOfWork )
+ if( source is not DbContext unitOfWork )
return false;
return await unitOfWork.Database.EnsureDeletedAsync();
}
@@ -78,7 +78,7 @@ public static async Task EnsureDeletedAsync( this IUnitOfWork source ) {
/// 工作单元
public static void ClearCache( this IUnitOfWork source ) {
source.CheckNull( nameof( source ) );
- if ( source is not UnitOfWorkBase unitOfWork )
+ if ( source is not DbContext unitOfWork )
return;
unitOfWork.ChangeTracker.Clear();
}
@@ -89,7 +89,7 @@ public static void ClearCache( this IUnitOfWork source ) {
/// 工作单元
public static string GetChangeTrackerDebugView( this IUnitOfWork source ) {
source.CheckNull( nameof( source ) );
- if( source is not UnitOfWorkBase unitOfWork )
+ if( source is not DbContext unitOfWork )
return null;
unitOfWork.ChangeTracker.DetectChanges();
return unitOfWork.ChangeTracker.DebugView.LongView;
@@ -101,8 +101,20 @@ public static string GetChangeTrackerDebugView( this IUnitOfWork source ) {
/// 工作单元
public static bool IsChange( this IUnitOfWork source ) {
source.CheckNull( nameof( source ) );
- if ( source is not UnitOfWorkBase unitOfWork )
+ if ( source is not DbContext unitOfWork )
return false;
return unitOfWork.ChangeTracker.Entries().Any( t => t.State == EntityState.Modified );
}
+
+ ///
+ /// 是否可连接
+ ///
+ /// 工作单元
+ /// 取消令牌
+ public static async Task CanConnectAsync( this IUnitOfWork source, CancellationToken cancellationToken = default ) {
+ source.CheckNull( nameof( source ) );
+ if ( source is not DbContext unitOfWork )
+ return false;
+ return await unitOfWork.Database.CanConnectAsync( cancellationToken );
+ }
}
\ No newline at end of file
diff --git a/src/Util.Data.EntityFrameworkCore/Usings.cs b/src/Util.Data.EntityFrameworkCore/Usings.cs
index 8bbcd04d1..bdf0a4378 100644
--- a/src/Util.Data.EntityFrameworkCore/Usings.cs
+++ b/src/Util.Data.EntityFrameworkCore/Usings.cs
@@ -3,36 +3,19 @@
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
-global using System.Diagnostics;
global using System.Text;
-global using System.IO;
-global using System.Data;
-global using System.Linq.Dynamic.Core;
global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
global using System.Text.Json;
global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
global using System.Text.Encodings.Web;
global using System.Text.Json.Serialization;
global using System.Text.Unicode;
-global using System.Data.Common;
-global using System.Buffers;
-global using System.Collections;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
global using System.ComponentModel.DataAnnotations.Schema;
-global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Microsoft.EntityFrameworkCore;
global using Microsoft.EntityFrameworkCore.ChangeTracking;
global using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
global using Microsoft.EntityFrameworkCore.Metadata;
-global using Microsoft.EntityFrameworkCore.Infrastructure;
\ No newline at end of file
diff --git a/src/Util.Data.Metadata/Usings.cs b/src/Util.Data.Metadata/Usings.cs
index c6554431f..e8a5e3a49 100644
--- a/src/Util.Data.Metadata/Usings.cs
+++ b/src/Util.Data.Metadata/Usings.cs
@@ -1,31 +1,3 @@
-global using System;
-global using System.Threading.Tasks;
+global using System.Threading.Tasks;
global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
global using System.Data;
-global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Collections;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
\ No newline at end of file
diff --git a/src/Util.Data.Sql/Usings.cs b/src/Util.Data.Sql/Usings.cs
index c6554431f..c1dab6d39 100644
--- a/src/Util.Data.Sql/Usings.cs
+++ b/src/Util.Data.Sql/Usings.cs
@@ -2,30 +2,7 @@
global using System.Threading.Tasks;
global using System.Collections.Generic;
global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
global using System.Text;
-global using System.IO;
global using System.Data;
-global using System.Linq.Dynamic.Core;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
global using System.Collections;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
\ No newline at end of file
diff --git a/src/Util.Domain.Biz/Usings.cs b/src/Util.Domain.Biz/Usings.cs
index 8f2f1d4fa..5558ed8ff 100644
--- a/src/Util.Domain.Biz/Usings.cs
+++ b/src/Util.Domain.Biz/Usings.cs
@@ -1,28 +1 @@
-global using System;
-global using System.Threading.Tasks;
-global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
\ No newline at end of file
+global using System.ComponentModel;
diff --git a/src/Util.Domain/Usings.cs b/src/Util.Domain/Usings.cs
index 8f2f1d4fa..39f0dc68b 100644
--- a/src/Util.Domain/Usings.cs
+++ b/src/Util.Domain/Usings.cs
@@ -3,26 +3,7 @@
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
-global using System.Diagnostics;
global using System.Text;
-global using System.IO;
global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
\ No newline at end of file
+global using System.ComponentModel.DataAnnotations;
\ No newline at end of file
diff --git a/src/Util.Events.Abstractions/Usings.cs b/src/Util.Events.Abstractions/Usings.cs
index 62ad476d2..74f57adbd 100644
--- a/src/Util.Events.Abstractions/Usings.cs
+++ b/src/Util.Events.Abstractions/Usings.cs
@@ -1,8 +1,3 @@
global using System;
global using System.Threading.Tasks;
-global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
\ No newline at end of file
+global using System.Threading;
\ No newline at end of file
diff --git a/src/Util.Events/Infrastructure/LocalEventBusServiceRegistrar.cs b/src/Util.Events/Infrastructure/LocalEventBusServiceRegistrar.cs
index 4f3f3a418..fca0582a0 100644
--- a/src/Util.Events/Infrastructure/LocalEventBusServiceRegistrar.cs
+++ b/src/Util.Events/Infrastructure/LocalEventBusServiceRegistrar.cs
@@ -38,8 +38,8 @@ public Action Register( ServiceContext serviceContext ) {
/// 注册依赖
///
private void RegisterDependency( IServiceCollection services ) {
- services.TryAddSingleton();
- services.TryAddSingleton();
+ services.TryAddTransient();
+ services.TryAddTransient();
}
///
diff --git a/src/Util.Events/Usings.cs b/src/Util.Events/Usings.cs
index 62ad476d2..e92039a8a 100644
--- a/src/Util.Events/Usings.cs
+++ b/src/Util.Events/Usings.cs
@@ -3,6 +3,5 @@
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
-global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.DependencyInjection.Extensions;
\ No newline at end of file
diff --git a/src/Util.FileStorage.Minio/Usings.cs b/src/Util.FileStorage.Minio/Usings.cs
index 001ad83c2..f1afe42f1 100644
--- a/src/Util.FileStorage.Minio/Usings.cs
+++ b/src/Util.FileStorage.Minio/Usings.cs
@@ -3,29 +3,9 @@
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
global using System.Net.Http;
-global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Minio;
global using Minio.Exceptions;
\ No newline at end of file
diff --git a/src/Util.FileStorage/Usings.cs b/src/Util.FileStorage/Usings.cs
index 8f2f1d4fa..51e7d135d 100644
--- a/src/Util.FileStorage/Usings.cs
+++ b/src/Util.FileStorage/Usings.cs
@@ -1,28 +1,5 @@
global using System;
global using System.Threading.Tasks;
global using System.Collections.Generic;
-global using System.Linq;
global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
\ No newline at end of file
diff --git a/src/Util.Generators.Razor/Usings.cs b/src/Util.Generators.Razor/Usings.cs
index 2dce8b6f5..6db9905e7 100644
--- a/src/Util.Generators.Razor/Usings.cs
+++ b/src/Util.Generators.Razor/Usings.cs
@@ -1,29 +1,5 @@
global using System;
global using System.Threading.Tasks;
global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.Data;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
global using Microsoft.Extensions.DependencyInjection.Extensions;
\ No newline at end of file
diff --git a/src/Util.Generators/Usings.cs b/src/Util.Generators/Usings.cs
index 92b8c3c09..97692f7e9 100644
--- a/src/Util.Generators/Usings.cs
+++ b/src/Util.Generators/Usings.cs
@@ -2,29 +2,8 @@
global using System.Threading.Tasks;
global using System.Collections.Generic;
global using System.Linq;
-global using System.Threading;
global using System.Diagnostics;
-global using System.Text;
global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
global using System.Data;
global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Humanizer;
diff --git a/src/Util.Images.Avatar/Usings.cs b/src/Util.Images.Avatar/Usings.cs
index e28169e43..759c7debf 100644
--- a/src/Util.Images.Avatar/Usings.cs
+++ b/src/Util.Images.Avatar/Usings.cs
@@ -1,39 +1,5 @@
global using System;
global using System.Threading.Tasks;
-global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using System.Collections.Concurrent;
-global using System.Numerics;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
-global using SixLabors.ImageSharp;
global using SixLabors.Fonts;
-global using SixLabors.ImageSharp.Drawing.Processing;
-global using SixLabors.ImageSharp.Processing;
-global using SixLabors.ImageSharp.PixelFormats;
-global using SixLabors.ImageSharp.Formats;
-global using SixLabors.ImageSharp.Formats.Bmp;
-global using SixLabors.ImageSharp.Formats.Gif;
-global using SixLabors.ImageSharp.Formats.Jpeg;
-global using SixLabors.ImageSharp.Formats.Png;
\ No newline at end of file
diff --git a/src/Util.Images.ImageSharp/Usings.cs b/src/Util.Images.ImageSharp/Usings.cs
index e28169e43..c1e13363e 100644
--- a/src/Util.Images.ImageSharp/Usings.cs
+++ b/src/Util.Images.ImageSharp/Usings.cs
@@ -1,32 +1,10 @@
-global using System;
-global using System.Threading.Tasks;
+global using System.Threading.Tasks;
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
global using System.Collections.Concurrent;
global using System.Numerics;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
-global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using SixLabors.ImageSharp;
global using SixLabors.Fonts;
global using SixLabors.ImageSharp.Drawing.Processing;
diff --git a/src/Util.Localization/01-Util.Localization.csproj b/src/Util.Localization/01-Util.Localization.csproj
index f0d73486e..53cb902e6 100644
--- a/src/Util.Localization/01-Util.Localization.csproj
+++ b/src/Util.Localization/01-Util.Localization.csproj
@@ -5,7 +5,7 @@
icon.jpg
Util.Localization
Util.Localization
- Util.Localization是Util应用框架的本地化封装类库
+ Util.Localization是Util应用框架的Json本地化操作类库
@@ -27,7 +27,11 @@
-
+
+
+
+
+
diff --git a/src/Util.Localization/AppBuilderExtensions.cs b/src/Util.Localization/AppBuilderExtensions.cs
index 3b8a219f3..b6b909882 100644
--- a/src/Util.Localization/AppBuilderExtensions.cs
+++ b/src/Util.Localization/AppBuilderExtensions.cs
@@ -34,4 +34,33 @@ public static IAppBuilder AddJsonLocalization( this IAppBuilder builder, string
} );
return builder;
}
+
+ ///
+ /// 配置Json本地化
+ ///
+ /// 应用生成器
+ /// Json本地化配置操作
+ public static IAppBuilder AddJsonLocalization( this IAppBuilder builder, Action setupAction ) {
+ builder.CheckNull( nameof( builder ) );
+ var options = new JsonLocalizationOptions();
+ setupAction?.Invoke( options );
+ builder.AddJsonLocalization( options.ResourcesPath );
+ if( options.Cultures == null || options.Cultures.Count == 0 )
+ return builder;
+ builder.Host.ConfigureServices( ( _, services ) => {
+ services.Configure( localizationOptions => {
+ var supportedCultures = options.Cultures.Select( culture => new CultureInfo( culture ) ).ToList();
+ localizationOptions.DefaultRequestCulture = new RequestCulture( culture: supportedCultures[0], uiCulture: supportedCultures[0] );
+ localizationOptions.SupportedCultures = supportedCultures;
+ localizationOptions.SupportedUICultures = supportedCultures;
+ localizationOptions.AddInitialRequestCultureProvider( new CustomRequestCultureProvider( async context => {
+ var culture = context.Request.Headers.ContentLanguage.FirstOrDefault();
+ if ( culture.IsEmpty() )
+ culture = "zh-CN";
+ return await Task.FromResult( new ProviderCultureResult( culture ) );
+ } ) );
+ } );
+ } );
+ return builder;
+ }
}
\ No newline at end of file
diff --git a/src/Util.Localization/JsonLocalizationOptions.cs b/src/Util.Localization/JsonLocalizationOptions.cs
new file mode 100644
index 000000000..ae29cfe02
--- /dev/null
+++ b/src/Util.Localization/JsonLocalizationOptions.cs
@@ -0,0 +1,24 @@
+namespace Util.Localization;
+
+///
+/// Json本地化配置
+///
+public class JsonLocalizationOptions {
+ ///
+ /// 初始化Json本地化配置
+ ///
+ public JsonLocalizationOptions() {
+ ResourcesPath = "Resources";
+ Cultures = new List();
+ }
+
+ ///
+ /// 资源路径
+ ///
+ public string ResourcesPath { get; set; }
+
+ ///
+ /// 语言文化
+ ///
+ public IList Cultures { get; set; }
+}
\ No newline at end of file
diff --git a/src/Util.Localization/Usings.cs b/src/Util.Localization/Usings.cs
index e3fc17cc4..cb32b443a 100644
--- a/src/Util.Localization/Usings.cs
+++ b/src/Util.Localization/Usings.cs
@@ -1,29 +1,15 @@
global using System;
-global using System.Threading.Tasks;
global using System.Collections.Generic;
global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
global using System.IO;
global using System.Reflection;
-global using System.ComponentModel;
global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
+global using System.Threading.Tasks;
global using System.Collections.Concurrent;
+global using Microsoft.AspNetCore.Builder;
+global using Microsoft.AspNetCore.Localization;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Microsoft.Extensions.Localization;
\ No newline at end of file
diff --git a/src/Util.Logging.Serilog.Exceptionless/Usings.cs b/src/Util.Logging.Serilog.Exceptionless/Usings.cs
index 21bd97608..f5414d916 100644
--- a/src/Util.Logging.Serilog.Exceptionless/Usings.cs
+++ b/src/Util.Logging.Serilog.Exceptionless/Usings.cs
@@ -1,32 +1,6 @@
global using System;
-global using System.Threading.Tasks;
-global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Serilog;
-global using Serilog.Core;
-global using Serilog.Events;
-global using Serilog.Configuration;
global using Exceptionless;
\ No newline at end of file
diff --git a/src/Util.Logging.Serilog/AppBuilderExtensions.cs b/src/Util.Logging.Serilog/AppBuilderExtensions.cs
index f1df39afc..b416cbf3d 100644
--- a/src/Util.Logging.Serilog/AppBuilderExtensions.cs
+++ b/src/Util.Logging.Serilog/AppBuilderExtensions.cs
@@ -21,16 +21,41 @@ public static IAppBuilder AddSerilog( this IAppBuilder builder ) {
/// 应用生成器
/// 是否清除默认设置的日志提供程序
public static IAppBuilder AddSerilog( this IAppBuilder builder, bool isClearProviders ) {
+ return builder.AddSerilog( options => {
+ options.IsClearProviders = isClearProviders;
+ } );
+ }
+
+ ///
+ /// 配置Serilog日志操作
+ ///
+ /// 应用生成器
+ /// 应用程序名称
+ public static IAppBuilder AddSerilog( this IAppBuilder builder, string appName ) {
+ return builder.AddSerilog( options => {
+ options.Application = appName;
+ } );
+ }
+
+ ///
+ /// 配置Serilog日志操作
+ ///
+ /// 应用生成器
+ /// 日志配置操作
+ public static IAppBuilder AddSerilog( this IAppBuilder builder, Action setupAction ) {
builder.CheckNull( nameof( builder ) );
+ var options = new LogOptions();
+ setupAction?.Invoke( options );
builder.Host.ConfigureServices( ( context, services ) => {
services.AddSingleton();
services.AddTransient( typeof( ILog<> ), typeof( Log<> ) );
services.AddTransient( typeof( ILog ), t => t.GetService()?.CreateLog( "default" ) ?? NullLog.Instance );
var configuration = context.Configuration;
services.AddLogging( loggingBuilder => {
- if ( isClearProviders )
+ if ( options.IsClearProviders )
loggingBuilder.ClearProviders();
SerilogLog.Logger = new LoggerConfiguration()
+ .Enrich.WithProperty( "Application", options.Application )
.Enrich.FromLogContext()
.Enrich.WithLogLevel()
.Enrich.WithLogContext()
diff --git a/src/Util.Logging.Serilog/Enrichers/LogContextEnricher.cs b/src/Util.Logging.Serilog/Enrichers/LogContextEnricher.cs
index f338447e9..03882eb1f 100644
--- a/src/Util.Logging.Serilog/Enrichers/LogContextEnricher.cs
+++ b/src/Util.Logging.Serilog/Enrichers/LogContextEnricher.cs
@@ -6,11 +6,6 @@ namespace Util.Logging.Serilog.Enrichers;
/// 日志上下文扩展属性
///
public class LogContextEnricher : ILogEventEnricher {
- ///
- /// 日志上下文
- ///
- private LogContext _context;
-
///
/// 扩展属性
///
@@ -20,16 +15,20 @@ public void Enrich( LogEvent logEvent, ILogEventPropertyFactory propertyFactory
var accessor = Ioc.Create();
if ( accessor == null )
return;
- _context = accessor.Context;
- if ( _context == null )
+ var context = accessor.Context;
+ if ( context == null )
+ return;
+ if ( logEvent == null )
+ return;
+ if ( propertyFactory == null )
return;
RemoveProperties( logEvent );
- AddDuration( logEvent, propertyFactory );
- AddTraceId( logEvent, propertyFactory );
- AddUserId( logEvent, propertyFactory );
- AddApplication( logEvent, propertyFactory );
- AddEnvironment( logEvent, propertyFactory );
- AddData( logEvent, propertyFactory );
+ AddDuration( context,logEvent, propertyFactory );
+ AddTraceId( context, logEvent, propertyFactory );
+ AddUserId( context, logEvent, propertyFactory );
+ AddApplication( context, logEvent, propertyFactory );
+ AddEnvironment( context, logEvent, propertyFactory );
+ AddData( context, logEvent, propertyFactory );
}
///
@@ -46,60 +45,60 @@ private void RemoveProperties( LogEvent logEvent ) {
///
/// 添加执行持续时间
///
- private void AddDuration( LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
- if ( _context.Stopwatch == null )
+ private void AddDuration( LogContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
+ if ( context?.Stopwatch == null )
return;
- var property = propertyFactory.CreateProperty( "Duration", _context.Stopwatch.Elapsed.Description() );
+ var property = propertyFactory.CreateProperty( "Duration", context.Stopwatch.Elapsed.Description() );
logEvent.AddOrUpdateProperty( property );
}
///
/// 添加跟踪号
///
- private void AddTraceId( LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
- if ( _context.TraceId.IsEmpty() )
+ private void AddTraceId( LogContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
+ if ( context == null || context.TraceId.IsEmpty() )
return;
- var property = propertyFactory.CreateProperty( "TraceId", _context.TraceId );
+ var property = propertyFactory.CreateProperty( "TraceId", context.TraceId );
logEvent.AddOrUpdateProperty( property );
}
///
/// 添加用户标识
///
- private void AddUserId( LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
- if ( _context.UserId.IsEmpty() )
+ private void AddUserId( LogContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
+ if ( context == null || context.UserId.IsEmpty() )
return;
- var property = propertyFactory.CreateProperty( "UserId", _context.UserId );
+ var property = propertyFactory.CreateProperty( "UserId", context.UserId );
logEvent.AddOrUpdateProperty( property );
}
///
/// 添加应用程序
///
- private void AddApplication( LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
- if ( _context.Application.IsEmpty() )
+ private void AddApplication( LogContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
+ if ( context == null || context.Application.IsEmpty() )
return;
- var property = propertyFactory.CreateProperty( "Application", _context.Application );
+ var property = propertyFactory.CreateProperty( "Application", context.Application );
logEvent.AddOrUpdateProperty( property );
}
///
/// 添加执行环境
///
- private void AddEnvironment( LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
- if ( _context.Environment.IsEmpty() )
+ private void AddEnvironment( LogContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
+ if ( context == null || context.Environment.IsEmpty() )
return;
- var property = propertyFactory.CreateProperty( "Environment", _context.Environment );
+ var property = propertyFactory.CreateProperty( "Environment", context.Environment );
logEvent.AddOrUpdateProperty( property );
}
///
/// 添加扩展数据
///
- private void AddData( LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
- if ( _context.Data.Count == 0 )
+ private void AddData( LogContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
+ if ( context?.Data == null || context.Data.Count == 0 )
return;
- foreach ( var item in _context.Data ) {
+ foreach ( var item in context.Data ) {
var property = propertyFactory.CreateProperty( item.Key, item.Value );
logEvent.AddOrUpdateProperty( property );
}
diff --git a/src/Util.Logging.Serilog/LogOptions.cs b/src/Util.Logging.Serilog/LogOptions.cs
new file mode 100644
index 000000000..b06e1e80b
--- /dev/null
+++ b/src/Util.Logging.Serilog/LogOptions.cs
@@ -0,0 +1,15 @@
+namespace Util.Logging.Serilog;
+
+///
+/// 日志配置
+///
+public class LogOptions {
+ ///
+ /// 是否清除默认设置的日志提供程序
+ ///
+ public bool IsClearProviders { get; set; }
+ ///
+ /// 应用程序名称
+ ///
+ public string Application { get; set; }
+}
\ No newline at end of file
diff --git a/src/Util.Logging.Serilog/Usings.cs b/src/Util.Logging.Serilog/Usings.cs
index 8a7aee74f..e3d303199 100644
--- a/src/Util.Logging.Serilog/Usings.cs
+++ b/src/Util.Logging.Serilog/Usings.cs
@@ -1,30 +1,7 @@
global using System;
-global using System.Threading.Tasks;
-global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
-global using System.Diagnostics;
-global using System.Text;
-global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
global using Serilog;
global using Serilog.Core;
global using Serilog.Events;
diff --git a/src/Util.Logging/Usings.cs b/src/Util.Logging/Usings.cs
index d95c3e216..cf49b8375 100644
--- a/src/Util.Logging/Usings.cs
+++ b/src/Util.Logging/Usings.cs
@@ -1,27 +1,5 @@
global using System;
-global using System.Threading.Tasks;
global using System.Collections.Generic;
-global using System.Linq;
-global using System.Threading;
global using System.Diagnostics;
global using System.Text;
-global using System.IO;
-global using System.Reflection;
-global using System.ComponentModel;
-global using System.Globalization;
-global using System.Text.Json;
-global using System.Linq.Expressions;
-global using System.Text.RegularExpressions;
-global using System.ComponentModel.DataAnnotations;
-global using System.Runtime.InteropServices;
-global using System.Text.Encodings.Web;
-global using System.Text.Json.Serialization;
-global using System.Text.Unicode;
-global using System.Buffers;
-global using System.Diagnostics.CodeAnalysis;
-global using Microsoft.Extensions.Configuration;
-global using Microsoft.Extensions.DependencyInjection;
-global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
-global using Microsoft.Extensions.Logging.Abstractions;
-global using Microsoft.Extensions.DependencyInjection.Extensions;
\ No newline at end of file
diff --git a/src/Util.Microservices.Dapr/03-Util.Microservices.Dapr.csproj b/src/Util.Microservices.Dapr/03-Util.Microservices.Dapr.csproj
new file mode 100644
index 000000000..6ce924357
--- /dev/null
+++ b/src/Util.Microservices.Dapr/03-Util.Microservices.Dapr.csproj
@@ -0,0 +1,40 @@
+
+
+ $(NetTargetFramework)
+ icon.jpg
+ Util.Microservices.Dapr
+ Util.Microservices.Dapr
+ Util.Microservices.Dapr是Util应用框架基于Dapr的微服务操作类库
+
+
+
+
+ .\obj\Debug\$(NetTargetFramework)\Util.Microservices.Dapr.xml
+
+
+
+
+ .\obj\Release\$(NetTargetFramework)\Util.Microservices.Dapr.xml
+
+
+
+
+ True
+ False
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Util.Microservices.Dapr/AppBuilderExtensions.cs b/src/Util.Microservices.Dapr/AppBuilderExtensions.cs
new file mode 100644
index 000000000..c36f10d28
--- /dev/null
+++ b/src/Util.Microservices.Dapr/AppBuilderExtensions.cs
@@ -0,0 +1,96 @@
+using System.Text.Encodings.Web;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Text.Unicode;
+using Util.Configs;
+using Util.Helpers;
+using Util.SystemTextJson;
+
+namespace Util.Microservices.Dapr;
+
+///
+/// Dapr微服务操作扩展
+///
+public static class AppBuilderExtensions {
+ ///
+ /// 配置Dapr微服务操作
+ ///
+ /// 应用生成器
+ public static IAppBuilder AddDapr( this IAppBuilder builder ) {
+ return builder.AddDapr( null );
+ }
+
+ ///
+ /// 配置Dapr微服务操作
+ ///
+ /// 应用生成器
+ /// Dapr配置操作
+ public static IAppBuilder AddDapr( this IAppBuilder builder, Action setupAction ) {
+ return builder.AddDapr( setupAction, null );
+ }
+
+ ///
+ /// 配置Dapr微服务操作
+ ///
+ /// 应用生成器
+ /// Dapr配置操作
+ /// Dapr客户端生成操作
+ public static IAppBuilder AddDapr( this IAppBuilder builder, Action setupAction, Action buildAction ) {
+ var options = new DaprOptions();
+ setupAction?.Invoke( options );
+ builder.CheckNull( nameof( builder ) );
+ builder.Host.ConfigureServices( ( context, services ) => {
+ services.AddDaprClient( clientBuilder => {
+ clientBuilder.UseJsonSerializationOptions( GetJsonSerializerOptions() );
+ buildAction?.Invoke( clientBuilder );
+ } );
+ if( setupAction != null )
+ services.Configure( setupAction );
+ } );
+ builder.Host.ConfigureAppConfiguration( ( context, configurationBuilder ) => {
+ AddDaprSecretStore( configurationBuilder, options, buildAction );
+ } );
+ return builder;
+ }
+
+ ///
+ /// 获取Json序列化配置
+ ///
+ private static JsonSerializerOptions GetJsonSerializerOptions() {
+ return new JsonSerializerOptions {
+ PropertyNameCaseInsensitive = true,
+ NumberHandling = JsonNumberHandling.AllowReadingFromString,
+ Encoder = JavaScriptEncoder.Create( UnicodeRanges.All ),
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ Converters = {
+ new DateTimeJsonConverter(),
+ new NullableDateTimeJsonConverter()
+ }
+ };
+ }
+
+ ///
+ /// 配置Dapr机密存储器
+ ///
+ private static void AddDaprSecretStore( IConfigurationBuilder configurationBuilder , DaprOptions options, Action buildAction ) {
+ if ( options.SecretStoreName.IsEmpty() )
+ return;
+ try {
+ configurationBuilder.AddDaprSecretStore( options.SecretStoreName, CreateDaprClient( buildAction ) );
+ }
+ catch ( Exception ) {
+ if ( Common.IsLinux )
+ throw;
+ }
+ }
+
+ ///
+ /// 创建Dapr客户端
+ ///
+ private static DaprClient CreateDaprClient( Action buildAction ) {
+ var clientBuilder = new DaprClientBuilder();
+ clientBuilder.UseJsonSerializationOptions( GetJsonSerializerOptions() );
+ buildAction?.Invoke( clientBuilder );
+ return clientBuilder.Build();
+ }
+}
\ No newline at end of file
diff --git a/src/Util.Microservices.Dapr/CommandLines/DaprRunCommand.cs b/src/Util.Microservices.Dapr/CommandLines/DaprRunCommand.cs
new file mode 100644
index 000000000..53946d616
--- /dev/null
+++ b/src/Util.Microservices.Dapr/CommandLines/DaprRunCommand.cs
@@ -0,0 +1,269 @@
+using System.Net.Sockets;
+using System.Net;
+using Util.Helpers;
+
+namespace Util.Microservices.Dapr.CommandLines;
+
+///
+/// dapr run 命令
+///
+public class DaprRunCommand {
+ ///
+ /// 日志操作
+ ///
+ private ILogger _logger;
+ ///
+ /// 应用标识
+ ///
+ private string _appId;
+ ///
+ /// 应用端口
+ ///
+ private int _appPort;
+ ///
+ /// 应用访问协议
+ ///
+ private string _appProtocol;
+ ///
+ /// Dapr Http端口
+ ///
+ private int _daprHttpPort;
+ ///
+ /// Dapr Grpc端口
+ ///
+ private int _daprGrpcPort;
+ ///
+ /// 度量端口
+ ///
+ private int _metricsPort;
+ ///
+ /// Dapr组件配置目录路径
+ ///
+ private string _componentsPath;
+ ///
+ /// Dapr配置目录路径
+ ///
+ private string _configPath;
+ ///
+ /// dotnet项目文件路径
+ ///
+ private string _project;
+ ///
+ /// 是否使用空闲端口
+ ///
+ private bool _isUseFreePorts;
+
+ ///
+ /// 封闭构造方法
+ ///
+ private DaprRunCommand() {
+ _logger = NullLogger.Instance;
+ }
+
+ ///
+ /// 创建dapr run命令
+ ///
+ /// 应用标识
+ public static DaprRunCommand Create( string appId ) {
+ return new DaprRunCommand().AppId( appId );
+ }
+
+ ///
+ /// 获取应用协议
+ ///
+ public string GetAppProtocol() {
+ return _appProtocol;
+ }
+
+ ///
+ /// 获取应用端口
+ ///
+ public int GetAppPort() {
+ return _appPort;
+ }
+
+ ///
+ /// 获取Dapr Http端口
+ ///
+ public int GetDaprHttpPort() {
+ return _daprHttpPort;
+ }
+
+ ///
+ /// 获取Dapr Grpc端口
+ ///
+ public int GetDaprGrpcPort() {
+ return _daprGrpcPort;
+ }
+
+ ///
+ /// 获取度量端口
+ ///
+ public int GetMetricsPort() {
+ return _metricsPort;
+ }
+
+ ///
+ /// 设置应用标识
+ ///
+ /// 应用标识
+ private DaprRunCommand AppId( string id ) {
+ _appId = id;
+ return this;
+ }
+
+ ///
+ /// 设置日志操作
+ ///
+ public DaprRunCommand Log( ILogger logger ) {
+ _logger = logger;
+ return this;
+ }
+
+ ///
+ /// 设置应用端口,如果未设置则自动获取
+ ///
+ /// 应用Http端口
+ public DaprRunCommand AppPort( int port ) {
+ _appPort = port;
+ return this;
+ }
+
+ ///
+ /// 设置Dapr访问应用协议
+ ///
+ /// 访问协议,可选值为: Http,Grpc,默认值为: Http
+ public DaprRunCommand AppProtocol( string protocol ) {
+ _appProtocol = protocol;
+ return this;
+ }
+
+ ///
+ /// 设置Dapr Http端口,如果未设置则自动获取
+ ///
+ /// Dapr Http端口
+ public DaprRunCommand DaprHttpPort( int port ) {
+ _daprHttpPort = port;
+ return this;
+ }
+
+ ///
+ /// 设置Dapr Grpc端口,如果未设置则自动获取
+ ///
+ /// Dapr Grpc端口
+ public DaprRunCommand DaprGrpcPort( int port ) {
+ _daprGrpcPort = port;
+ return this;
+ }
+
+ ///
+ /// 设置度量端口,如果未设置则自动获取
+ ///
+ /// 度量端口
+ public DaprRunCommand MetricsPort( int port ) {
+ _metricsPort = port;
+ return this;
+ }
+
+ ///
+ /// 设置Dapr组件配置目录路径
+ ///
+ /// Dapr组件配置目录路径
+ public DaprRunCommand ComponentsPath( string path ) {
+ _componentsPath = path;
+ return this;
+ }
+
+ ///
+ /// 设置Dapr配置目录路径
+ ///
+ /// Dapr配置目录路径
+ public DaprRunCommand ConfigPath( string path ) {
+ _configPath = path;
+ return this;
+ }
+
+ ///
+ /// 设置dotnet项目文件路径
+ ///
+ /// dotnet项目文件路径,范例: ../../test/app.csproj
+ public DaprRunCommand Project( string project ) {
+ _project = project;
+ return this;
+ }
+
+ ///
+ /// 设置或取消使用空闲端口
+ ///
+ /// 是否使用空闲端口
+ public DaprRunCommand UseFreePorts( bool isUseFreePorts = true ) {
+ _isUseFreePorts = isUseFreePorts;
+ return this;
+ }
+
+ ///
+ /// 执行命令
+ ///
+ public void Execute() {
+ CreateCommandLine()
+ .OutputToMatch( "dapr initialized. Status: Running." )
+ .Execute();
+ }
+
+ ///
+ /// 创建命令行操作
+ ///
+ private CommandLine CreateCommandLine() {
+ if ( _isUseFreePorts )
+ GetFreePorts();
+ return CommandLine.Create( "dapr" )
+ .Log( _logger )
+ .Arguments( "run" )
+ .Arguments( "--app-id", _appId )
+ .ArgumentsIf( _appPort != 0, "--app-port", _appPort.ToString( CultureInfo.InvariantCulture ) )
+ .ArgumentsIf( _appProtocol.IsEmpty() == false, "--app-protocol", _appProtocol )
+ .ArgumentsIf( _daprHttpPort != 0, "--dapr-http-port", _daprHttpPort.ToString( CultureInfo.InvariantCulture ) )
+ .ArgumentsIf( _daprGrpcPort != 0, "--dapr-grpc-port", _daprGrpcPort.ToString( CultureInfo.InvariantCulture ) )
+ .ArgumentsIf( _metricsPort != 0, "--metrics-port", _metricsPort.ToString( CultureInfo.InvariantCulture ) )
+ .ArgumentsIf( _componentsPath.IsEmpty() == false, "--resources-path", _componentsPath )
+ .ArgumentsIf( _configPath.IsEmpty() == false, "--config", _configPath )
+ .Arguments( "--log-level", "debug" )
+ .Arguments( "--" )
+ .Arguments( "dotnet", "run" )
+ .ArgumentsIf( _project.IsEmpty() == false, "--project", _project )
+ .ArgumentsIf( _appPort != 0, "--urls", $"http://localhost:{_appPort.ToString( CultureInfo.InvariantCulture )}" );
+ }
+
+ ///
+ /// 获取空闲端口
+ ///
+ private void GetFreePorts() {
+ const int NUM_LISTENERS = 4;
+ IPAddress ip = IPAddress.Loopback;
+ var listeners = new TcpListener[NUM_LISTENERS];
+ var ports = new int[NUM_LISTENERS];
+ for ( int i = 0; i < NUM_LISTENERS; i++ ) {
+ listeners[i] = new TcpListener( ip, 0 );
+ listeners[i].Start();
+ ports[i] = ( (IPEndPoint)listeners[i].LocalEndpoint ).Port;
+ }
+ for ( int i = 0; i < NUM_LISTENERS; i++ ) {
+ listeners[i].Stop();
+ }
+ if ( _appPort == 0 )
+ _appPort = ports[0];
+ if ( _daprHttpPort == 0 )
+ _daprHttpPort = ports[1];
+ if ( _daprGrpcPort == 0 )
+ _daprGrpcPort = ports[2];
+ if ( _metricsPort == 0 )
+ _metricsPort = ports[3];
+ }
+
+ ///
+ /// 获取命令调试文本
+ ///
+ public string GetDebugText() {
+ return CreateCommandLine().GetDebugText();
+ }
+}
\ No newline at end of file
diff --git a/src/Util.Microservices.Dapr/CommandLines/DaprStopCommand.cs b/src/Util.Microservices.Dapr/CommandLines/DaprStopCommand.cs
new file mode 100644
index 000000000..28e016362
--- /dev/null
+++ b/src/Util.Microservices.Dapr/CommandLines/DaprStopCommand.cs
@@ -0,0 +1,76 @@
+using Util.Helpers;
+
+namespace Util.Microservices.Dapr.CommandLines;
+
+///
+/// dapr stop命令
+///
+public class DaprStopCommand {
+ ///
+ /// 日志操作
+ ///
+ private ILogger _logger;
+ ///
+ /// 应用标识
+ ///
+ private string _appId;
+
+ ///
+ /// 封闭构造方法
+ ///
+ private DaprStopCommand() {
+ _logger = NullLogger.Instance;
+ }
+
+ ///
+ /// 创建dapr stop命令
+ ///
+ /// 应用标识
+ public static DaprStopCommand Create( string appId ) {
+ return new DaprStopCommand().AppId( appId );
+ }
+
+ ///
+ /// 设置应用标识
+ ///
+ /// 应用标识
+ private DaprStopCommand AppId( string id ) {
+ _appId = id;
+ return this;
+ }
+
+ ///
+ /// 设置日志操作
+ ///
+ public DaprStopCommand Log( ILogger logger ) {
+ _logger = logger;
+ return this;
+ }
+
+ ///
+ /// 执行命令
+ ///
+ public void Execute() {
+ CreateCommandLine()
+ .OutputToMatch( "app stopped successfully" )
+ .OutputToMatch( "failed to stop app id" )
+ .Execute();
+ }
+
+ ///
+ /// 创建命令行操作
+ ///
+ private CommandLine CreateCommandLine() {
+ return CommandLine.Create( "dapr" )
+ .Log( _logger )
+ .Arguments( "stop" )
+ .Arguments( "--app-id", _appId );
+ }
+
+ ///
+ /// 获取命令调试文本
+ ///
+ public string GetDebugText() {
+ return CreateCommandLine().GetDebugText();
+ }
+}
\ No newline at end of file
diff --git a/src/Util.Microservices.Dapr/DaprEventBus.cs b/src/Util.Microservices.Dapr/DaprEventBus.cs
new file mode 100644
index 000000000..d13f7f345
--- /dev/null
+++ b/src/Util.Microservices.Dapr/DaprEventBus.cs
@@ -0,0 +1,70 @@
+using Util.Data;
+using Util.Events;
+
+namespace Util.Microservices.Dapr;
+
+///
+/// 基于Dapr的集成事件总线
+///
+public class DaprEventBus : IIntegrationEventBus {
+ ///
+ /// Dapr客户端
+ ///
+ private readonly DaprClient _client;
+ ///
+ /// 日志操作
+ ///
+ private readonly ILogger _logger;
+ ///
+ /// 工作单元操作管理器
+ ///
+ private readonly IUnitOfWorkActionManager _actionManager;
+
+ ///
+ /// 发布订阅配置名称,默认值: pubsub
+ ///
+ public static string PubsubName { get; set; } = "pubsub";
+
+ ///
+ /// 初始化Dapr集成事件总线
+ ///
+ /// Dapr客户端
+ /// 日志操作
+ /// 工作单元操作管理器
+ public DaprEventBus( DaprClient client, ILogger logger, IUnitOfWorkActionManager actionManager ) {
+ _client = client ?? throw new ArgumentNullException( nameof( client ) );
+ _logger = logger ?? throw new ArgumentNullException( nameof( logger ) );
+ _actionManager = actionManager ?? throw new ArgumentNullException( nameof( actionManager ) );
+ }
+
+ ///
+ /// 发布事件
+ ///
+ /// 事件类型
+ /// 事件
+ /// 是否立即发送事件,默认为true,如果希望发送操作延迟到工作单元提交成功后,则设置为false
+ /// 主题名称,默认使用类型名称作为主题
+ /// 发布订阅配置名称,默认值: pubsub
+ /// 取消令牌
+ public async Task PublishAsync( TEvent @event, bool sendNow = true, string topic = "", string pubsubName = "", CancellationToken cancellationToken = default )
+ where TEvent : IIntegrationEvent {
+ @event.CheckNull( nameof( @event ) );
+ if ( sendNow ) {
+ await PublishEventAsync( @event, topic, pubsubName, cancellationToken );
+ return;
+ }
+ _actionManager.Register( async () => {
+ await PublishEventAsync( @event, topic, pubsubName, cancellationToken );
+ } );
+ }
+
+ ///
+ /// 发布事件
+ ///
+ private async Task PublishEventAsync( TEvent @event, string topic, string pubsubName, CancellationToken cancellationToken ) {
+ pubsubName = pubsubName.IsEmpty() ? PubsubName : pubsubName;
+ topic = topic.IsEmpty() ? @event.GetType().Name : topic;
+ _logger.LogInformation( "Publishing event {@Event} to {PubsubName}.{Topic}", @event, pubsubName, topic );
+ await _client.PublishEventAsync( pubsubName, topic, (object)@event, cancellationToken );
+ }
+}
\ No newline at end of file
diff --git a/src/Util.Microservices.Dapr/DaprMicroserviceClient.cs b/src/Util.Microservices.Dapr/DaprMicroserviceClient.cs
new file mode 100644
index 000000000..ba7f0051a
--- /dev/null
+++ b/src/Util.Microservices.Dapr/DaprMicroserviceClient.cs
@@ -0,0 +1,31 @@
+using Util.Microservices.Dapr.ServiceInvocations;
+
+namespace Util.Microservices.Dapr;
+
+///
+/// Dapr微服务客户端
+///
+public class DaprMicroserviceClient : IMicroserviceClient {
+ ///
+ /// 初始化Dapr微服务客户端
+ ///
+ /// Dapr客户端
+ /// Dapr Http客户端
+ /// Dapr配置
+ /// 应用标识
+ /// 日志工厂
+ public DaprMicroserviceClient( DaprClient client, HttpClient httpClient, IOptions options, string appId, ILoggerFactory loggerFactory ) {
+ HttpClient = new HttpClientService().SetHttpClient( httpClient );
+ ServiceInvocation = new DaprServiceInvocation( client, options, loggerFactory ).Service( appId );
+ }
+
+ ///
+ /// Http客户端
+ ///
+ public IHttpClient HttpClient { get; }
+
+ ///
+ /// WebApi服务调用
+ ///
+ public IServiceInvocation ServiceInvocation { get; }
+}
\ No newline at end of file
diff --git a/src/Util.Microservices.Dapr/DaprMicroserviceClientFactory.cs b/src/Util.Microservices.Dapr/DaprMicroserviceClientFactory.cs
new file mode 100644
index 000000000..7d88e00d9
--- /dev/null
+++ b/src/Util.Microservices.Dapr/DaprMicroserviceClientFactory.cs
@@ -0,0 +1,93 @@
+namespace Util.Microservices.Dapr;
+
+///
+/// Dapr微服务客户端工厂
+///
+public class DaprMicroserviceClientFactory : IMicroserviceClientFactory {
+ ///
+ /// Dapr客户端
+ ///
+ private readonly DaprClient _client;
+ ///
+ /// 应用标识
+ ///
+ private string _appId;
+ ///
+ /// Dapr Http端口
+ ///
+ private int _daprHttpPort;
+ ///
+ /// Dapr配置
+ ///
+ private readonly IOptions _options;
+ ///
+ /// 日志工厂
+ ///
+ private readonly ILoggerFactory _loggerFactory;
+
+
+ ///
+ /// 初始化Dapr微服务客户端生成器
+ ///
+ /// Dapr客户端
+ /// Dapr配置
+ /// 日志工厂
+ public DaprMicroserviceClientFactory( DaprClient client = null, IOptions options = null, ILoggerFactory loggerFactory = null ) {
+ _client = client;
+ _options = options;
+ _loggerFactory = loggerFactory;
+ }
+
+ ///
+ /// 设置应用标识
+ ///
+ /// 应用标识
+ public void AppId( string appId ) {
+ _appId = appId;
+ }
+
+ ///
+ /// 设置Dapr Http端口
+ ///
+ /// Dapr Http端口
+ public void DaprHttpPort( int daprHttpPort ) {
+ _daprHttpPort = daprHttpPort;
+ }
+
+ ///
+ public virtual IMicroserviceClient Create() {
+ var client = CreateDaprClient();
+ var httpClient = CreateHttpClient();
+ return new DaprMicroserviceClient( client, httpClient, _options, _appId, _loggerFactory );
+ }
+
+ ///
+ /// 创建Dapr客户端
+ ///
+ protected virtual DaprClient CreateDaprClient() {
+ var httpEndpoint = GetDaprHttpEndpoint();
+ if ( httpEndpoint.IsEmpty() == false ) {
+ return new DaprClientBuilder()
+ .UseHttpEndpoint( httpEndpoint )
+ .Build();
+ }
+ return _client ?? new DaprClientBuilder().Build();
+ }
+
+ ///
+ /// 获取Dapr Http端点
+ ///
+ protected virtual string GetDaprHttpEndpoint() {
+ return _daprHttpPort > 0 ? $"http://localhost:{_daprHttpPort}" : null;
+ }
+
+ ///
+ /// 创建Dapr Http客户端
+ ///
+ protected virtual HttpClient CreateHttpClient() {
+ if ( _appId.IsEmpty() )
+ return DaprClient.CreateInvokeHttpClient();
+ var endpoint = GetDaprHttpEndpoint();
+ return endpoint.IsEmpty() ? DaprClient.CreateInvokeHttpClient( _appId ) : DaprClient.CreateInvokeHttpClient( _appId, endpoint );
+ }
+}
\ No newline at end of file
diff --git a/src/Util.Microservices.Dapr/DaprOptions.cs b/src/Util.Microservices.Dapr/DaprOptions.cs
new file mode 100644
index 000000000..23fef2152
--- /dev/null
+++ b/src/Util.Microservices.Dapr/DaprOptions.cs
@@ -0,0 +1,22 @@
+namespace Util.Microservices.Dapr;
+
+///
+/// Dapr配置
+///
+public class DaprOptions {
+ ///
+ /// 初始化Dapr配置
+ ///
+ public DaprOptions() {
+ ServiceInvocation = new ServiceInvocationOptions();
+ }
+
+ ///
+ /// 机密存储器名称
+ ///
+ public string SecretStoreName { get; set; }
+ ///
+ /// 服务调用配置
+ ///
+ public ServiceInvocationOptions ServiceInvocation { get; set; }
+}
\ No newline at end of file
diff --git a/src/Util.Microservices.Dapr/IMicroserviceClientFactoryExtensions.cs b/src/Util.Microservices.Dapr/IMicroserviceClientFactoryExtensions.cs
new file mode 100644
index 000000000..77cbff955
--- /dev/null
+++ b/src/Util.Microservices.Dapr/IMicroserviceClientFactoryExtensions.cs
@@ -0,0 +1,28 @@
+namespace Util.Microservices.Dapr;
+
+///
+/// 微服务客户端工厂扩展
+///
+public static class IMicroserviceClientFactoryExtensions {
+ ///
+ /// 设置应用标识
+ ///
+ /// 微服务客户端工厂
+ /// 应用标识
+ public static IMicroserviceClientFactory AppId( this IMicroserviceClientFactory source,string appId ) {
+ if ( source is DaprMicroserviceClientFactory factory )
+ factory.AppId( appId );
+ return source;
+ }
+
+ ///
+ /// 设置Dapr Http端口
+ ///
+ /// 微服务客户端工厂
+ /// Dapr Http端口
+ public static IMicroserviceClientFactory DaprHttpPort( this IMicroserviceClientFactory source, int daprHttpPort ) {
+ if ( source is DaprMicroserviceClientFactory factory )
+ factory.DaprHttpPort( daprHttpPort );
+ return source;
+ }
+}
\ No newline at end of file
diff --git a/src/Util.Microservices.Dapr/ServiceInvocationOptions.cs b/src/Util.Microservices.Dapr/ServiceInvocationOptions.cs
new file mode 100644
index 000000000..d44af9694
--- /dev/null
+++ b/src/Util.Microservices.Dapr/ServiceInvocationOptions.cs
@@ -0,0 +1,61 @@
+namespace Util.Microservices.Dapr;
+
+///
+/// 服务调用配置
+///
+public class ServiceInvocationOptions {
+ ///
+ /// 初始化服务调用配置
+ ///
+ public ServiceInvocationOptions() {
+ RequestFilters = new List();
+ ResponseFilters = new List();
+ ImportHeaderKeys = new List {
+ "Authorization",
+ "x-correlation-id",
+ "Content-Language"
+ };
+ IsUnpackResult = true;
+ }
+
+ ///
+ /// 是否使用ServiceResult对结果解包
+ ///
+ public bool IsUnpackResult { get; set; }
+ ///
+ /// 服务状态码转换事件,参数为业务状态码或Http状态码,取决于是否使用约定结果类型
+ ///
+ public Func OnState { get; set; }
+ ///
+ /// 调用前事件,返回false取消调用
+ ///
+ public Func OnBefore { get; set; }
+ ///
+ /// 调用成功事件
+ ///
+ public Func OnSuccess { get; set; }
+ ///
+ /// 调用失败事件
+ ///
+ public Func OnFail { get; set; }
+ ///
+ /// 调用未授权事件
+ ///
+ public Func OnUnauthorized { get; set; }
+ ///
+ /// 调用完成事件
+ ///
+ public Func OnComplete { get; set; }
+ ///
+ /// 请求过滤器集合
+ ///
+ public IList RequestFilters { get; set; }
+ ///
+ /// 响应过滤器集合
+ ///
+ public IList ResponseFilters { get; set; }
+ ///
+ /// 需要导入的请求头键名集合,从当前Http上下文导入
+ ///
+ public IList ImportHeaderKeys { get; set; }
+}
\ No newline at end of file
diff --git a/src/Util.Microservices.Dapr/ServiceInvocations/DaprServiceInvocation.cs b/src/Util.Microservices.Dapr/ServiceInvocations/DaprServiceInvocation.cs
new file mode 100644
index 000000000..540b81577
--- /dev/null
+++ b/src/Util.Microservices.Dapr/ServiceInvocations/DaprServiceInvocation.cs
@@ -0,0 +1,555 @@
+using System.Net;
+
+namespace Util.Microservices.Dapr.ServiceInvocations;
+
+///
+/// Dapr WebApi服务调用操作
+///
+public class DaprServiceInvocation : DaprServiceInvocationBase, IServiceInvocation {
+
+ #region 构造方法
+
+ ///
+ /// 初始化Dapr WebApi服务调用操作
+ ///
+ /// Dapr客户端
+ /// Dapr配置
+ /// 日志工厂
+ public DaprServiceInvocation( DaprClient client, IOptions options, ILoggerFactory loggerFactory ) : base( client, options, loggerFactory ) {
+ }
+
+ #endregion
+
+ #region 事件
+
+ ///
+ /// 调用前事件
+ ///
+ protected Func OnBeforeAction { get; set; }
+ ///
+ /// 响应结果转换事件
+ ///
+ protected Func> OnResultAction { get; set; }
+ ///
+ /// 调用后事件
+ ///
+ protected Action OnAfterAction { get; set; }
+ ///
+ /// 调用成功事件
+ ///
+ protected Func OnSuccessAction { get; set; }
+ ///
+ /// 调用失败事件
+ ///
+ protected Func OnFailAction { get; set; }
+ ///
+ /// 调用未授权事件
+ ///
+ protected Func OnUnauthorizedAction { get; set; }
+ ///
+ /// 调用完成事件
+ ///
+ protected Func OnCompleteAction { get; set; }
+
+ ///
+ public IServiceInvocation OnBefore( Func action ) {
+ OnBeforeAction = action;
+ return this;
+ }
+
+ ///
+ /// 响应结果转换事件
+ ///
+ /// 响应结果转换操作
+ public IServiceInvocation OnResult( Func> action ) {
+ OnResultAction = action;
+ return this;
+ }
+
+ ///
+ /// 调用后事件
+ ///
+ /// 调用后处理操作
+ public IServiceInvocation OnAfter( Action action ) {
+ OnAfterAction = action;
+ return this;
+ }
+
+ ///
+ public IServiceInvocation OnSuccess( Func action ) {
+ if ( action != null )
+ OnSuccessAction = ( request, response, result ) => action( request, response, (TResponse)result );
+ return this;
+ }
+
+ ///
+ /// 调用失败事件
+ ///
+ /// 调用失败处理操作
+ public IServiceInvocation OnFail( Func action ) {
+ OnFailAction = action;
+ return this;
+ }
+
+ ///
+ /// 调用未授权事件
+ ///
+ /// 调用未授权处理操作
+ public IServiceInvocation OnUnauthorized( Func action ) {
+ OnUnauthorizedAction = action;
+ return this;
+ }
+
+ ///
+ /// 调用完成事件
+ ///
+ /// 调用完成处理操作
+ public IServiceInvocation OnComplete( Func action ) {
+ OnCompleteAction = action;
+ return this;
+ }
+
+ #endregion
+
+ #region 方法调用重载
+
+ ///
+ public async Task InvokeAsync( string methodName, CancellationToken cancellationToken = default ) {
+ await InvokeAsync( methodName, HttpMethod.Get, cancellationToken );
+ }
+
+ ///
+ public async Task InvokeAsync( string methodName, HttpMethod httpMethod, CancellationToken cancellationToken = default ) {
+ await InvokeAsync