diff --git a/.husky/commit-msg b/.husky/commit-msg
index 764265f1..32539ddd 100644
--- a/.husky/commit-msg
+++ b/.husky/commit-msg
@@ -1,8 +1,8 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
-dotnet tool update -g dotnet-execute --prerelease
-dotnet husky run --name "commit-message-linter" --args "$1"
+# dotnet tool update -g dotnet-execute --prerelease
+# dotnet husky run --name "commit-message-linter" --args "$1"
echo
echo Great work! 🥂
diff --git a/.husky/scripts/commit-lint.cs b/.husky/scripts/commit-lint.cs
index 8a7500cc..a3c0850f 100644
--- a/.husky/scripts/commit-lint.cs
+++ b/.husky/scripts/commit-lint.cs
@@ -9,7 +9,10 @@ A simple regex commit linter
var msg = File.ReadAllLines(args[0])[0];
Console.WriteLine("Your commit headline message is:\n> {0}", msg);
if (System.Text.RegularExpressions.Regex.IsMatch(msg, pattern))
- return 0;
+ return 0;
+
+if (msg.StartsWith("Merge branch "))
+ return 0;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid commit message");
diff --git a/LICENSE b/LICENSE
index a29d1281..c5d2a42c 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,21 +1,201 @@
-MIT License
-
-Copyright (c) 2017-2019 liweihan
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2017 WeihanLi
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/README.md b/README.md
index 65084f23..50f2acf0 100644
--- a/README.md
+++ b/README.md
@@ -6,9 +6,9 @@
[![WeihanLi.Common Latest](https://img.shields.io/nuget/vpre/WeihanLi.Common)](https://www.nuget.org/packages/WeihanLi.Common/absoluteLatest)
-[![Pipelines Build Status](https://weihanli.visualstudio.com/Pipelines/_apis/build/status/WeihanLi.WeihanLi.Common?branchName=dev)](https://weihanli.visualstudio.com/Pipelines/_build/latest?definitionId=16&branchName=dev)
+[![Azure Pipelines Build Status](https://weihanli.visualstudio.com/Pipelines/_apis/build/status/WeihanLi.WeihanLi.Common?branchName=dev)](https://weihanli.visualstudio.com/Pipelines/_build/latest?definitionId=16&branchName=dev)
-[![Github Build Status](https://github.com/WeihanLi/WeihanLi.Common/workflows/dotnetcore/badge.svg?branch=dev)](https://github.com/WeihanLi/WeihanLi.Common/actions?query=workflow%3Adotnetcore+branch%3Adev)
+[![Github Actions Build Status](https://github.com/WeihanLi/WeihanLi.Common/actions/workflows/default.yml/badge.svg)](https://github.com/WeihanLi/WeihanLi.Common/actions/workflows/default.yml)
## Intro
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index e06a5a3d..19297e62 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -36,3 +36,11 @@ steps:
displayName: 'Powershell Script'
env:
Nuget__ApiKey: $(nugetApiKey)
+
+# Publish code coverage results v2
+# Publish any of the code coverage results from a build.
+- task: PublishCodeCoverageResults@2
+ inputs:
+ summaryFileLocation: "$(System.DefaultWorkingDirectory)/**/coverage.cobertura.xml" # string. Required. Path to summary files.
+ #pathToSources: # string. Path to Source files.
+ #failIfCoverageEmpty: false # boolean. Fail if code coverage results are missing. Default: false.
\ No newline at end of file
diff --git a/build/build.cs b/build/build.cs
index 87122eb9..fa0d064d 100644
--- a/build/build.cs
+++ b/build/build.cs
@@ -51,7 +51,7 @@ await BuildProcess.CreateBuilder()
{
foreach (var project in testProjects)
{
- await ExecuteCommandAsync($"dotnet test {project}");
+ await ExecuteCommandAsync($"dotnet test --collect:\"XPlat Code Coverage;Format=cobertura,opencover;ExcludeByAttribute=ExcludeFromCodeCoverage,Obsolete,GeneratedCode,CompilerGeneratedAttribute\" {project}");
}
})
;
diff --git a/build/version.props b/build/version.props
index 85f81377..2c44b46c 100644
--- a/build/version.props
+++ b/build/version.props
@@ -2,7 +2,7 @@
10
- 61
+ 62$(VersionMajor).$(VersionMinor).$(VersionPatch)
diff --git a/samples/AspNetCoreSample/Events/EventConsumer.cs b/samples/AspNetCoreSample/Events/EventConsumer.cs
index c63fc92b..aa997819 100644
--- a/samples/AspNetCoreSample/Events/EventConsumer.cs
+++ b/samples/AspNetCoreSample/Events/EventConsumer.cs
@@ -3,16 +3,12 @@
namespace AspNetCoreSample.Events;
-public class EventConsumer : BackgroundService
+public class EventConsumer
+ (IEventQueue eventQueue, IEventHandlerFactory eventHandlerFactory)
+ : BackgroundService
{
- private readonly IEventQueue _eventQueue;
- private readonly IEventHandlerFactory _eventHandlerFactory;
-
- public EventConsumer(IEventQueue eventQueue, IEventHandlerFactory eventHandlerFactory)
- {
- _eventQueue = eventQueue;
- _eventHandlerFactory = eventHandlerFactory;
- }
+ private readonly IEventQueue _eventQueue = eventQueue;
+ private readonly IEventHandlerFactory _eventHandlerFactory = eventHandlerFactory;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
diff --git a/samples/AspNetCoreSample/FluentAspectsServiceProviderFactory.cs b/samples/AspNetCoreSample/FluentAspectsServiceProviderFactory.cs
index a4e54e70..543d962d 100644
--- a/samples/AspNetCoreSample/FluentAspectsServiceProviderFactory.cs
+++ b/samples/AspNetCoreSample/FluentAspectsServiceProviderFactory.cs
@@ -4,22 +4,15 @@
namespace AspNetCoreSample;
-internal sealed class FluentAspectsServiceProviderFactory : IServiceProviderFactory
+internal sealed class FluentAspectsServiceProviderFactory(
+ Action? optionsAction,
+ Action? aspectBuildAction,
+ Expression>? ignoreTypesPredict
+ ) : IServiceProviderFactory
{
- private readonly Action? _optionsAction;
- private readonly Action? _aspectBuildAction;
- private readonly Expression>? _ignoreTypesPredict;
-
- public FluentAspectsServiceProviderFactory(
- Action? optionsAction,
- Action? aspectBuildAction,
- Expression>? ignoreTypesPredict
- )
- {
- _optionsAction = optionsAction;
- _aspectBuildAction = aspectBuildAction;
- _ignoreTypesPredict = ignoreTypesPredict;
- }
+ private readonly Action? _optionsAction = optionsAction;
+ private readonly Action? _aspectBuildAction = aspectBuildAction;
+ private readonly Expression>? _ignoreTypesPredict = ignoreTypesPredict;
public IServiceCollection CreateBuilder(IServiceCollection services)
{
@@ -39,15 +32,12 @@ public static IHostBuilder UseFluentAspectsServiceProviderFactory(this IHostBuil
Action? aspectBuildAction = null,
Expression>? ignoreTypesPredict = null)
{
- if (ignoreTypesPredict == null)
- {
- ignoreTypesPredict = t =>
+ ignoreTypesPredict ??= t =>
t.HasNamespace() &&
(t.Namespace!.StartsWith("Microsoft.")
|| t.Namespace.StartsWith("System.")
)
;
- }
hostBuilder.UseServiceProviderFactory(
new FluentAspectsServiceProviderFactory(optionsAction, aspectBuildAction, ignoreTypesPredict)
);
diff --git a/samples/AspNetCoreSample/Startup.cs b/samples/AspNetCoreSample/Startup.cs
index c277e057..9d14f57f 100644
--- a/samples/AspNetCoreSample/Startup.cs
+++ b/samples/AspNetCoreSample/Startup.cs
@@ -4,14 +4,9 @@
namespace AspNetCoreSample;
-public class Startup
+public class Startup(IConfiguration configuration)
{
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration.ReplacePlaceholders();
- }
-
- public IConfiguration Configuration { get; }
+ public IConfiguration Configuration { get; } = configuration.ReplacePlaceholders();
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
diff --git a/samples/DotNetCoreSample/AppHostTest.cs b/samples/DotNetCoreSample/AppHostTest.cs
index 98d9741f..ce6ad1df 100644
--- a/samples/DotNetCoreSample/AppHostTest.cs
+++ b/samples/DotNetCoreSample/AppHostTest.cs
@@ -45,12 +45,8 @@ protected override Task ExecuteTaskAsync(CancellationToken stoppingToken)
}
}
-file sealed class DiagnosticBackgroundService : CronBasedBackgroundServiceWithDiagnostic
+file sealed class DiagnosticBackgroundService(IServiceProvider serviceProvider) : CronBasedBackgroundServiceWithDiagnostic(serviceProvider)
{
- public DiagnosticBackgroundService(IServiceProvider serviceProvider) : base(serviceProvider)
- {
- }
-
protected override string CronExpression => CronHelper.Secondly;
protected override Task ExecuteTaskInternalAsync(IServiceProvider serviceProvider, CancellationToken stoppingToken)
@@ -83,16 +79,11 @@ file interface IWebServer
Task StopAsync(CancellationToken cancellationToken);
}
-file sealed class HttpListenerWebServer : IWebServer
+file sealed class HttpListenerWebServer(IServiceProvider serviceProvider) : IWebServer
{
- private readonly IServiceProvider _serviceProvider;
+ private readonly IServiceProvider _serviceProvider = serviceProvider;
private readonly HttpListener _listener = new();
- public HttpListenerWebServer(IServiceProvider serviceProvider)
- {
- _serviceProvider = serviceProvider;
- }
-
public async Task StartAsync(CancellationToken cancellationToken)
{
_listener.Prefixes.Add("http://localhost:5100/");
@@ -127,14 +118,9 @@ public Task StopAsync(CancellationToken cancellationToken)
}
}
-file sealed class WebServerHostedService : BackgroundService
+file sealed class WebServerHostedService(IWebServer server) : BackgroundService
{
- private readonly IWebServer _server;
-
- public WebServerHostedService(IWebServer server)
- {
- _server = server;
- }
+ private readonly IWebServer _server = server;
public override async Task StopAsync(CancellationToken cancellationToken)
{
diff --git a/samples/DotNetCoreSample/AspectTest.cs b/samples/DotNetCoreSample/AspectTest.cs
index 6223e1a8..4155690e 100644
--- a/samples/DotNetCoreSample/AspectTest.cs
+++ b/samples/DotNetCoreSample/AspectTest.cs
@@ -6,12 +6,8 @@
namespace DotNetCoreSample;
-public class TestDbContext : DbContext
+public class TestDbContext(DbContextOptions dbContextOptions) : DbContext(dbContextOptions)
{
- public TestDbContext(DbContextOptions dbContextOptions) : base(dbContextOptions)
- {
- }
-
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// optionsBuilder.UseSqlServer(DbConnectionString);
diff --git a/samples/DotNetCoreSample/DataExtensionTest.cs b/samples/DotNetCoreSample/DataExtensionTest.cs
index d997321e..213644f0 100644
--- a/samples/DotNetCoreSample/DataExtensionTest.cs
+++ b/samples/DotNetCoreSample/DataExtensionTest.cs
@@ -36,13 +36,12 @@ [Token] [NVARCHAR](200) NULL,
public static void MainTest()
{
var connString = DependencyResolver.ResolveRequiredService().GetConnectionString("TestDb");
- using (var conn = new SqlConnection(connString))
- {
- Init(conn);
+ using var conn = new SqlConnection(connString);
+ Init(conn);
- for (int i = 0; i < 3; i++)
- {
- conn.Execute(@"INSERT INTO [dbo].[TestTable111]
+ for (var i = 0; i < 3; i++)
+ {
+ conn.Execute(@"INSERT INTO [dbo].[TestTable111]
(
[Token],
[CreatedTime]
@@ -51,17 +50,17 @@ public static void MainTest()
(@Token, --Token - nvarchar(200)
@CreatedTime-- CreatedTime - datetime
)", new TestEntity
- {
- Token = Guid.NewGuid().ToString("N") + "_Execute_Model",
- CreatedTime = DateTime.Now
- });
- }
+ {
+ Token = Guid.NewGuid().ToString("N") + "_Execute_Model",
+ CreatedTime = DateTime.Now
+ });
+ }
- Console.WriteLine("Current data count:{0}", conn.ExecuteScalarTo("SELECT COUNT(1) FROM [dbo].[TestTable111]"));
+ Console.WriteLine("Current data count:{0}", conn.ExecuteScalarTo("SELECT COUNT(1) FROM [dbo].[TestTable111]"));
- for (int i = 0; i < 3; i++)
- {
- conn.Execute(@"INSERT INTO [dbo].[TestTable111]
+ for (var i = 0; i < 3; i++)
+ {
+ conn.Execute(@"INSERT INTO [dbo].[TestTable111]
(
[Token],
[CreatedTime]
@@ -70,16 +69,16 @@ public static void MainTest()
(@Token, --Token - nvarchar(200)
GETDATE()-- CreatedTime - datetime
)", new TestEntity
- {
- Token = Guid.NewGuid().ToString("N") + "_Execute_Model_1"
- });
- }
+ {
+ Token = Guid.NewGuid().ToString("N") + "_Execute_Model_1"
+ });
+ }
- Console.WriteLine("Current data count:{0}", conn.ExecuteScalarTo("SELECT COUNT(1) FROM [dbo].[TestTable111]"));
+ Console.WriteLine("Current data count:{0}", conn.ExecuteScalarTo("SELECT COUNT(1) FROM [dbo].[TestTable111]"));
- for (int i = 0; i < 3; i++)
- {
- conn.Execute(@"INSERT INTO [dbo].[TestTable111]
+ for (var i = 0; i < 3; i++)
+ {
+ conn.Execute(@"INSERT INTO [dbo].[TestTable111]
(
[Token],
[CreatedTime]
@@ -88,35 +87,34 @@ public static void MainTest()
(@Token, --Token - nvarchar(200)
GETDATE()-- CreatedTime - datetime
)", new
- {
- Token = Guid.NewGuid().ToString("N") + "_Execute_Anonymous_Model"
- });
- }
-
- Console.WriteLine("Current data count:{0}", conn.ExecuteScalarTo("SELECT COUNT(1) FROM [dbo].[TestTable111]"));
+ {
+ Token = Guid.NewGuid().ToString("N") + "_Execute_Anonymous_Model"
+ });
+ }
- var tokens = conn.QueryColumn("SELECT Token FROM [dbo].[TestTable111]");
- Console.WriteLine("tokens:{0}", string.Join(",", tokens));
+ Console.WriteLine("Current data count:{0}", conn.ExecuteScalarTo("SELECT COUNT(1) FROM [dbo].[TestTable111]"));
- var ids = conn.Select("SELECT PKID FROM [dbo].[TestTable111]");
- Console.WriteLine("ids:{0}", string.Join(",", ids));
+ var tokens = conn.QueryColumn("SELECT Token FROM [dbo].[TestTable111]");
+ Console.WriteLine("tokens:{0}", string.Join(",", tokens));
- var lastId = conn.Fetch("SELECT TOP 1 PKID FROM [dbo].[TestTable111] ORDER BY PKID DESC");
- Console.WriteLine("lastId:{0}", lastId);
+ var ids = conn.Select("SELECT PKID FROM [dbo].[TestTable111]");
+ Console.WriteLine("ids:{0}", string.Join(",", ids));
- conn.Execute("Delete from TestTable111 where PKID > @pkid", new { pkid = 888 });
+ var lastId = conn.Fetch("SELECT TOP 1 PKID FROM [dbo].[TestTable111] ORDER BY PKID DESC");
+ Console.WriteLine("lastId:{0}", lastId);
- Console.WriteLine("Current data count:{0}", conn.ExecuteScalarTo("SELECT COUNT(1) FROM [dbo].[TestTable111]"));
+ conn.Execute("Delete from TestTable111 where PKID > @pkid", new { pkid = 888 });
- Console.WriteLine(conn.Fetch("select top 1 * from TestTable111")?.Token);
+ Console.WriteLine("Current data count:{0}", conn.ExecuteScalarTo("SELECT COUNT(1) FROM [dbo].[TestTable111]"));
- foreach (var entity in conn.Select("select * from TestTable111"))
- {
- Console.WriteLine(entity.Token);
- }
+ Console.WriteLine(conn.Fetch("select top 1 * from TestTable111")?.Token);
- Clean(conn);
+ foreach (var entity in conn.Select("select * from TestTable111"))
+ {
+ Console.WriteLine(entity.Token);
}
+
+ Clean(conn);
}
private static void Clean(DbConnection conn)
diff --git a/samples/DotNetCoreSample/LoggerTest.cs b/samples/DotNetCoreSample/LoggerTest.cs
index 74e94010..ffa7fa4e 100644
--- a/samples/DotNetCoreSample/LoggerTest.cs
+++ b/samples/DotNetCoreSample/LoggerTest.cs
@@ -55,14 +55,9 @@ public static void MicrosoftLoggingTest()
.Test();
}
- private class GenericTest
+ private class GenericTest(ILogger> logger)
{
- private readonly ILogger> _logger;
-
- public GenericTest(ILogger> logger)
- {
- _logger = logger;
- }
+ private readonly ILogger> _logger = logger;
public void Test() => _logger.LogInformation("test");
}
diff --git a/samples/DotNetCoreSample/NewtonJsonFormatter.cs b/samples/DotNetCoreSample/NewtonJsonFormatter.cs
index 685f1455..283f0011 100644
--- a/samples/DotNetCoreSample/NewtonJsonFormatter.cs
+++ b/samples/DotNetCoreSample/NewtonJsonFormatter.cs
@@ -15,16 +15,11 @@ public sealed class NewtonJsonFormatterOptions : ConsoleFormatterOptions
{
}
-public sealed class NewtonJsonFormatter : ConsoleFormatter
+public sealed class NewtonJsonFormatter(IOptions options) : ConsoleFormatter(FormatterName)
{
public const string FormatterName = "NewtonJson";
- private readonly NewtonJsonFormatterOptions _options;
-
- public NewtonJsonFormatter(IOptions options) : base(FormatterName)
- {
- _options = options.Value;
- }
+ private readonly NewtonJsonFormatterOptions _options = options.Value;
public override void Write(in LogEntry logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter)
{
diff --git a/samples/DotNetCoreSample/ProcessExecutorTest.cs b/samples/DotNetCoreSample/ProcessExecutorTest.cs
index b5de2401..dd8fdfe9 100644
--- a/samples/DotNetCoreSample/ProcessExecutorTest.cs
+++ b/samples/DotNetCoreSample/ProcessExecutorTest.cs
@@ -7,33 +7,31 @@ public class ProcessExecutorTest
{
public static void RawProcessTest()
{
- using (var process = new Process()
+ using var process = new Process()
{
StartInfo = new ProcessStartInfo("dotnet", "--info"),
EnableRaisingEvents = true,
- })
- {
- process.StartInfo.UseShellExecute = false;
- process.StartInfo.RedirectStandardOutput = true;
- process.StartInfo.RedirectStandardInput = true;
- process.StartInfo.RedirectStandardError = true;
+ };
+ process.StartInfo.UseShellExecute = false;
+ process.StartInfo.RedirectStandardOutput = true;
+ process.StartInfo.RedirectStandardInput = true;
+ process.StartInfo.RedirectStandardError = true;
- process.OutputDataReceived += (sender, args) =>
- {
- Console.WriteLine(args.Data);
- };
- process.Exited += (sender, args) =>
+ process.OutputDataReceived += (sender, args) =>
+ {
+ Console.WriteLine(args.Data);
+ };
+ process.Exited += (sender, args) =>
+ {
+ if (sender is Process _process)
{
- if (sender is Process _process)
- {
- Console.WriteLine($"The Process({_process.Id}) exited with code({_process.ExitCode})");
- }
- };
- process.Start();
- process.BeginOutputReadLine();
+ Console.WriteLine($"The Process({_process.Id}) exited with code({_process.ExitCode})");
+ }
+ };
+ process.Start();
+ process.BeginOutputReadLine();
- process.WaitForExit();
- }
+ process.WaitForExit();
}
public static void DotNetInfoTest()
@@ -60,7 +58,7 @@ public static void DotNetNugetGlobalPackagesInfoTest()
if (str.StartsWith("global-packages:"))
{
- folder = str.Substring("global-packages:".Length).Trim();
+ folder = str["global-packages:".Length..].Trim();
}
};
executor.Execute();
diff --git a/samples/DotNetCoreSample/Program.cs b/samples/DotNetCoreSample/Program.cs
index 6f2f0867..bda532d9 100644
--- a/samples/DotNetCoreSample/Program.cs
+++ b/samples/DotNetCoreSample/Program.cs
@@ -312,7 +312,7 @@
//TotpTest.MainTest();
// exit test
-// var exitToken = InvokeHelper.GetExitToken();
+// var exitToken = ApplicationHelper.ExitToken;
// exitToken.Register(() =>
// {
// Console.WriteLine(@"Exiting");
@@ -337,6 +337,16 @@
// GC.Collect();
// GC.WaitForPendingFinalizers();
+// await CommandExecutor.ExecuteCommandAndOutputAsync(
+// "dotnet build \"C:\\projects\\sources\\dotnet-exec\\src\\dotnet-exec\\dotnet-exec.csproj\"");
+
+{
+ var cts = CancellationTokenSource.CreateLinkedTokenSource(ApplicationHelper.ExitToken, default);
+ var registration = cts.Token.Register(() => Console.WriteLine(@"Exited"));
+ cts.Dispose();
+ // registration would be disposed when cts dispose
+}
+
await InvokeHelper.TryInvokeAsync(TemplatingSample.MainTest);
ConsoleHelper.ReadKeyWithPrompt("Press any key to exit");
diff --git a/samples/DotNetCoreSample/RepositoryTest.cs b/samples/DotNetCoreSample/RepositoryTest.cs
index b30bcf1c..d94bfeaa 100644
--- a/samples/DotNetCoreSample/RepositoryTest.cs
+++ b/samples/DotNetCoreSample/RepositoryTest.cs
@@ -60,14 +60,9 @@ public DbConnectionPool(IPooledObjectPolicy policy, int maximumRet
}
}
- public class DbConnectionPoolPolicy : IPooledObjectPolicy
+ public class DbConnectionPoolPolicy(string connString) : IPooledObjectPolicy
{
- private readonly string _connString;
-
- public DbConnectionPoolPolicy(string connString)
- {
- _connString = connString;
- }
+ private readonly string _connString = connString;
public DbConnection Create()
{
diff --git a/samples/DotNetCoreSample/RequestHelperTest.cs b/samples/DotNetCoreSample/RequestHelperTest.cs
index 5cdd6a75..f88867ea 100644
--- a/samples/DotNetCoreSample/RequestHelperTest.cs
+++ b/samples/DotNetCoreSample/RequestHelperTest.cs
@@ -23,7 +23,7 @@ public static void GetRequestParamTest()
Debug.Assert(param.HasKeys());
param = GetParamInfo("https://www.baidu.com/?tn=");
- Debug.Assert(param["tn"] == String.Empty);
+ Debug.Assert(param["tn"] == string.Empty);
}
private static NameValueCollection GetParamInfo(string url)
diff --git a/samples/DotNetCoreSample/ServiceDecoratorTest.cs b/samples/DotNetCoreSample/ServiceDecoratorTest.cs
index 161590d6..6e6a234a 100644
--- a/samples/DotNetCoreSample/ServiceDecoratorTest.cs
+++ b/samples/DotNetCoreSample/ServiceDecoratorTest.cs
@@ -34,13 +34,9 @@ public void Execute()
}
}
- private sealed class JobDecorator : IJob
+ private sealed class JobDecorator(IJob job) : IJob
{
- private readonly IJob _job;
- public JobDecorator(IJob job)
- {
- _job = job;
- }
+ private readonly IJob _job = job;
public string Name => $"??? {_job.Name}";
diff --git a/samples/DotNetCoreSample/TemplatingSample.cs b/samples/DotNetCoreSample/TemplatingSample.cs
index 56b327e5..b8bad829 100644
--- a/samples/DotNetCoreSample/TemplatingSample.cs
+++ b/samples/DotNetCoreSample/TemplatingSample.cs
@@ -7,7 +7,7 @@
namespace DotNetCoreSample;
-public class TemplatingSample
+public static class TemplatingSample
{
public static async Task MainTest()
{
@@ -37,7 +37,7 @@ public static async Task MainTest()
.AddInMemoryCollection([new("UserName1", "Test1234")])
.Build();
services.AddSingleton(configuration);
- services.AddTemplating();
+ services.AddTemplateEngine();
await using var provider = services.BuildServiceProvider();
var result = await provider.GetRequiredService()
.RenderAsync("Hello {{$config UserName1}}");
diff --git a/samples/DotNetCoreSample/TotpTest.cs b/samples/DotNetCoreSample/TotpTest.cs
index 44cb00f9..69cc4de6 100644
--- a/samples/DotNetCoreSample/TotpTest.cs
+++ b/samples/DotNetCoreSample/TotpTest.cs
@@ -14,8 +14,8 @@ public static void MainTest()
var totp = new Totp();
while (true)
{
- var code = totp.ComputeWithTtl(Base32EncodeHelper.GetBytes(secret));
- Console.WriteLine(@$"{code.Code} {code.Ttl}");
+ var (Code, Ttl) = totp.ComputeWithTtl(Base32EncodeHelper.GetBytes(secret));
+ Console.WriteLine(@$"{Code} {Ttl}");
ConsoleHelper.ReadLineWithPrompt();
}
}
diff --git a/src/WeihanLi.Common.Logging.Serilog/SerilogLogHelperProvider.cs b/src/WeihanLi.Common.Logging.Serilog/SerilogLogHelperProvider.cs
index dff45f39..12cf889f 100644
--- a/src/WeihanLi.Common.Logging.Serilog/SerilogLogHelperProvider.cs
+++ b/src/WeihanLi.Common.Logging.Serilog/SerilogLogHelperProvider.cs
@@ -7,7 +7,7 @@ namespace WeihanLi.Common.Logging.Serilog;
internal sealed class SerilogLogHelperProvider : ILogHelperProvider, IDisposable
{
- private static readonly MessageTemplateParser _messageTemplateParser = new MessageTemplateParser();
+ private static readonly MessageTemplateParser _messageTemplateParser = new();
public SerilogLogHelperProvider(LoggerConfiguration configuration)
{
@@ -46,37 +46,20 @@ public void Log(LogHelperLoggingEvent loggingEvent)
}
}
- private LogEventLevel GetSerilogEventLevel(LogHelperLogLevel logHelperLevel)
+ private static LogEventLevel GetSerilogEventLevel(LogHelperLogLevel logHelperLevel)
{
- switch (logHelperLevel)
+ return logHelperLevel switch
{
- case LogHelperLogLevel.All:
- return LogEventLevel.Verbose;
-
- case LogHelperLogLevel.Debug:
- return LogEventLevel.Debug;
-
- case LogHelperLogLevel.Info:
- return LogEventLevel.Information;
-
- case LogHelperLogLevel.Trace:
- return LogEventLevel.Debug;
-
- case LogHelperLogLevel.Warn:
- return LogEventLevel.Warning;
-
- case LogHelperLogLevel.Error:
- return LogEventLevel.Error;
-
- case LogHelperLogLevel.Fatal:
- return LogEventLevel.Fatal;
-
- case LogHelperLogLevel.None:
- return LogEventLevel.Fatal;
-
- default:
- return LogEventLevel.Warning;
- }
+ LogHelperLogLevel.All => LogEventLevel.Verbose,
+ LogHelperLogLevel.Debug => LogEventLevel.Debug,
+ LogHelperLogLevel.Info => LogEventLevel.Information,
+ LogHelperLogLevel.Trace => LogEventLevel.Debug,
+ LogHelperLogLevel.Warn => LogEventLevel.Warning,
+ LogHelperLogLevel.Error => LogEventLevel.Error,
+ LogHelperLogLevel.Fatal => LogEventLevel.Fatal,
+ LogHelperLogLevel.None => LogEventLevel.Fatal,
+ _ => LogEventLevel.Warning,
+ };
}
private const string SourceContextPropName = "SourceContext";
diff --git a/src/WeihanLi.Common.Logging.Serilog/SerilogLogger.cs b/src/WeihanLi.Common.Logging.Serilog/SerilogLogger.cs
index 4fa68574..bbe2293e 100644
--- a/src/WeihanLi.Common.Logging.Serilog/SerilogLogger.cs
+++ b/src/WeihanLi.Common.Logging.Serilog/SerilogLogger.cs
@@ -16,7 +16,7 @@ internal sealed class SerilogLogger : FrameworkLogger
private readonly SerilogLoggerProvider _provider;
private readonly ILogger _logger;
- private static readonly MessageTemplateParser _messageTemplateParser = new MessageTemplateParser();
+ private static readonly MessageTemplateParser _messageTemplateParser = new();
public SerilogLogger(
SerilogLoggerProvider provider,
@@ -67,7 +67,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except
}
else if (property.Key.StartsWith("@"))
{
- if (logger.BindProperty(property.Key.Substring(1), property.Value, true, out var destructured))
+ if (logger.BindProperty(property.Key[1..], property.Value, true, out var destructured))
properties.Add(destructured);
}
else
@@ -127,27 +127,16 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except
private static LogEventLevel ConvertLevel(LogLevel logLevel)
{
- switch (logLevel)
+ return logLevel switch
{
- case LogLevel.Critical:
- return LogEventLevel.Fatal;
-
- case LogLevel.Error:
- return LogEventLevel.Error;
-
- case LogLevel.Warning:
- return LogEventLevel.Warning;
-
- case LogLevel.Information:
- return LogEventLevel.Information;
-
- case LogLevel.Debug:
- return LogEventLevel.Debug;
+ LogLevel.Critical => LogEventLevel.Fatal,
+ LogLevel.Error => LogEventLevel.Error,
+ LogLevel.Warning => LogEventLevel.Warning,
+ LogLevel.Information => LogEventLevel.Information,
+ LogLevel.Debug => LogEventLevel.Debug,
// ReSharper disable once RedundantCaseLabel
- case LogLevel.Trace:
- default:
- return LogEventLevel.Verbose;
- }
+ _ => LogEventLevel.Verbose,
+ };
}
private static LogEventProperty CreateEventIdProperty(EventId eventId)
diff --git a/src/WeihanLi.Common.Logging.Serilog/SerilogLoggerProvider.cs b/src/WeihanLi.Common.Logging.Serilog/SerilogLoggerProvider.cs
index 0b54f20b..dd39f5a3 100644
--- a/src/WeihanLi.Common.Logging.Serilog/SerilogLoggerProvider.cs
+++ b/src/WeihanLi.Common.Logging.Serilog/SerilogLoggerProvider.cs
@@ -71,7 +71,7 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
if (scopeItem != null)
{
- scopeItems ??= new List();
+ scopeItems ??= [];
scopeItems.Add(scopeItem);
}
}
@@ -83,7 +83,7 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
}
}
- private readonly AsyncLocal _value = new AsyncLocal();
+ private readonly AsyncLocal _value = new();
internal SerilogLoggerScope? CurrentScope
{
diff --git a/src/WeihanLi.Common.Logging.Serilog/SerilogLoggerScope.cs b/src/WeihanLi.Common.Logging.Serilog/SerilogLoggerScope.cs
index 5cc98146..2d71d4e7 100644
--- a/src/WeihanLi.Common.Logging.Serilog/SerilogLoggerScope.cs
+++ b/src/WeihanLi.Common.Logging.Serilog/SerilogLoggerScope.cs
@@ -73,7 +73,7 @@ public void EnrichAndCreateScopeItem(LogEvent logEvent, ILogEventPropertyFactory
if (key.StartsWith("@"))
{
- key = key.Substring(1);
+ key = key[1..];
destructureObject = true;
}
diff --git a/src/WeihanLi.Common/Aspect/AspectInvokeException.cs b/src/WeihanLi.Common/Aspect/AspectInvokeException.cs
index bd8617ed..3f6ed0b7 100644
--- a/src/WeihanLi.Common/Aspect/AspectInvokeException.cs
+++ b/src/WeihanLi.Common/Aspect/AspectInvokeException.cs
@@ -1,11 +1,6 @@
namespace WeihanLi.Common.Aspect;
-public sealed class AspectInvokeException : Exception
+public sealed class AspectInvokeException(IInvocation invocation, Exception innerException) : Exception($"Invoke {invocation.ProxyMethod.Name} exception", innerException)
{
- public IInvocation Invocation { get; }
-
- public AspectInvokeException(IInvocation invocation, Exception innerException) : base($"Invoke {invocation.ProxyMethod.Name} exception", innerException)
- {
- Invocation = invocation;
- }
+ public IInvocation Invocation { get; } = invocation;
}
diff --git a/src/WeihanLi.Common/Aspect/DefaultProxyFactory.cs b/src/WeihanLi.Common/Aspect/DefaultProxyFactory.cs
index bc47d62d..11127b31 100644
--- a/src/WeihanLi.Common/Aspect/DefaultProxyFactory.cs
+++ b/src/WeihanLi.Common/Aspect/DefaultProxyFactory.cs
@@ -3,18 +3,13 @@
namespace WeihanLi.Common.Aspect;
-public sealed class DefaultProxyFactory : IProxyFactory
+public sealed class DefaultProxyFactory
+ (IProxyTypeFactory proxyTypeFactory, IServiceProvider? serviceProvider = null) : IProxyFactory
{
public static readonly IProxyFactory Instance = new DefaultProxyFactory(DefaultProxyTypeFactory.Instance);
- private readonly IProxyTypeFactory _proxyTypeFactory;
- private readonly IServiceProvider _serviceProvider;
-
- public DefaultProxyFactory(IProxyTypeFactory proxyTypeFactory, IServiceProvider? serviceProvider = null)
- {
- _proxyTypeFactory = proxyTypeFactory;
- _serviceProvider = serviceProvider ?? DependencyResolver.Current;
- }
+ private readonly IProxyTypeFactory _proxyTypeFactory = proxyTypeFactory;
+ private readonly IServiceProvider _serviceProvider = serviceProvider ?? DependencyResolver.Current;
[RequiresDynamicCode("Defining a dynamic assembly requires dynamic code.")]
[RequiresUnreferencedCode("Unreferenced code may be used")]
diff --git a/src/WeihanLi.Common/Aspect/DelegateInterceptor.cs b/src/WeihanLi.Common/Aspect/DelegateInterceptor.cs
index 75003cac..641a6eac 100644
--- a/src/WeihanLi.Common/Aspect/DelegateInterceptor.cs
+++ b/src/WeihanLi.Common/Aspect/DelegateInterceptor.cs
@@ -1,14 +1,9 @@
namespace WeihanLi.Common.Aspect;
[CLSCompliant(false)]
-public sealed class DelegateInterceptor : AbstractInterceptor
+public sealed class DelegateInterceptor(Func, Task> interceptFunc) : AbstractInterceptor
{
- private readonly Func, Task> _interceptFunc;
-
- public DelegateInterceptor(Func, Task> interceptFunc)
- {
- _interceptFunc = interceptFunc ?? throw new ArgumentNullException(nameof(interceptFunc));
- }
+ private readonly Func, Task> _interceptFunc = Guard.NotNull(interceptFunc);
public override Task Invoke(IInvocation invocation, Func next)
{
diff --git a/src/WeihanLi.Common/Aspect/FluentAspectOptions.cs b/src/WeihanLi.Common/Aspect/FluentAspectOptions.cs
index 06207968..1b0402cb 100644
--- a/src/WeihanLi.Common/Aspect/FluentAspectOptions.cs
+++ b/src/WeihanLi.Common/Aspect/FluentAspectOptions.cs
@@ -2,18 +2,18 @@
public sealed class FluentAspectOptions
{
- public readonly Dictionary, IInterceptionConfiguration> InterceptionConfigurations = new();
+ public readonly Dictionary, IInterceptionConfiguration> InterceptionConfigurations = [];
private IInterceptorResolver _interceptorResolver = FluentConfigInterceptorResolver.Instance;
- public HashSet> NoInterceptionConfigurations { get; } = new();
+ public HashSet> NoInterceptionConfigurations { get; } = [];
public IInterceptorResolver InterceptorResolver
{
get => _interceptorResolver;
- set => _interceptorResolver = value ?? throw new ArgumentNullException(nameof(value));
+ set => _interceptorResolver = Guard.NotNull(value);
}
- public HashSet Enrichers { get; } = new();
+ public HashSet Enrichers { get; } = [];
public IProxyFactory ProxyFactory { get; set; } = DefaultProxyFactory.Instance;
}
diff --git a/src/WeihanLi.Common/Aspect/FluentAspectOptionsExtensions.cs b/src/WeihanLi.Common/Aspect/FluentAspectOptionsExtensions.cs
index 010e4927..93e484ac 100644
--- a/src/WeihanLi.Common/Aspect/FluentAspectOptionsExtensions.cs
+++ b/src/WeihanLi.Common/Aspect/FluentAspectOptionsExtensions.cs
@@ -46,10 +46,7 @@ public static IInterceptionConfiguration InterceptMethod(this FluentAspectOpt
public static IInterceptionConfiguration InterceptMethod(this FluentAspectOptions options,
MethodInfo method)
{
- if (null == method)
- {
- throw new ArgumentNullException(nameof(method));
- }
+ Guard.NotNull(method);
var methodSignature = method.GetSignature();
return options.InterceptMethod(m => m.GetSignature().Equals(methodSignature));
@@ -58,10 +55,7 @@ public static IInterceptionConfiguration InterceptMethod(this FluentAspectOpt
public static IInterceptionConfiguration InterceptMethod(this FluentAspectOptions options,
MethodInfo method)
{
- if (null == method)
- {
- throw new ArgumentNullException(nameof(method));
- }
+ Guard.NotNull(method);
var methodSignature = method.GetSignature();
return options.InterceptMethod(m => m.GetSignature().Equals(methodSignature));
@@ -213,10 +207,7 @@ public static FluentAspectOptions NoInterceptMethod(this FluentAspectOptions opt
public static FluentAspectOptions NoInterceptMethod(this FluentAspectOptions options,
MethodInfo method)
{
- if (null == method)
- {
- throw new ArgumentNullException(nameof(method));
- }
+ Guard.NotNull(method);
var methodSignature = method.GetSignature();
return options.NoInterceptMethod(m => m.GetSignature().Equals(methodSignature));
@@ -225,10 +216,7 @@ public static FluentAspectOptions NoInterceptMethod(this FluentAspectOptions
public static FluentAspectOptions NoInterceptMethod(this FluentAspectOptions options,
MethodInfo method)
{
- if (null == method)
- {
- throw new ArgumentNullException(nameof(method));
- }
+ Guard.NotNull(method);
var methodSignature = method.GetSignature();
return options.NoInterceptMethod(m => m.GetSignature().Equals(methodSignature));
diff --git a/src/WeihanLi.Common/Aspect/FluentAspectsBuilder.cs b/src/WeihanLi.Common/Aspect/FluentAspectsBuilder.cs
index d586d4f7..ab269008 100644
--- a/src/WeihanLi.Common/Aspect/FluentAspectsBuilder.cs
+++ b/src/WeihanLi.Common/Aspect/FluentAspectsBuilder.cs
@@ -7,12 +7,7 @@ public interface IFluentAspectsBuilder
IServiceCollection Services { get; }
}
-internal sealed class FluentAspectsBuilder : IFluentAspectsBuilder
+internal sealed class FluentAspectsBuilder(IServiceCollection serviceCollection) : IFluentAspectsBuilder
{
- public FluentAspectsBuilder(IServiceCollection serviceCollection)
- {
- Services = serviceCollection;
- }
-
- public IServiceCollection Services { get; }
+ public IServiceCollection Services { get; } = serviceCollection;
}
diff --git a/src/WeihanLi.Common/Aspect/FluentAspectsServiceContainerBuilder.cs b/src/WeihanLi.Common/Aspect/FluentAspectsServiceContainerBuilder.cs
index 5b57f72f..da30a5bd 100644
--- a/src/WeihanLi.Common/Aspect/FluentAspectsServiceContainerBuilder.cs
+++ b/src/WeihanLi.Common/Aspect/FluentAspectsServiceContainerBuilder.cs
@@ -7,12 +7,7 @@ public interface IFluentAspectsServiceContainerBuilder
IServiceContainerBuilder Services { get; }
}
-internal sealed class FluentAspectsServiceContainerBuilder : IFluentAspectsServiceContainerBuilder
+internal sealed class FluentAspectsServiceContainerBuilder(IServiceContainerBuilder serviceCollection) : IFluentAspectsServiceContainerBuilder
{
- public FluentAspectsServiceContainerBuilder(IServiceContainerBuilder serviceCollection)
- {
- Services = serviceCollection;
- }
-
- public IServiceContainerBuilder Services { get; }
+ public IServiceContainerBuilder Services { get; } = serviceCollection;
}
diff --git a/src/WeihanLi.Common/Aspect/IInvocation.cs b/src/WeihanLi.Common/Aspect/IInvocation.cs
index 4053236b..24457b2c 100644
--- a/src/WeihanLi.Common/Aspect/IInvocation.cs
+++ b/src/WeihanLi.Common/Aspect/IInvocation.cs
@@ -53,7 +53,7 @@ public AspectInvocation(
ProxyTarget = proxyTarget;
Target = target;
Arguments = arguments;
- GenericArguments = methodBase?.GetGenericArguments() ?? Array.Empty();
+ GenericArguments = methodBase?.GetGenericArguments() ?? [];
if (proxyMethod.ContainsGenericParameters && GenericArguments.Length > 0)
{
@@ -64,6 +64,6 @@ public AspectInvocation(
ProxyMethod = proxyMethod;
}
- Properties = new Dictionary();
+ Properties = [];
}
}
diff --git a/src/WeihanLi.Common/Aspect/InvocationEnricherExtensions.cs b/src/WeihanLi.Common/Aspect/InvocationEnricherExtensions.cs
index b1f1cb43..e8810f0b 100644
--- a/src/WeihanLi.Common/Aspect/InvocationEnricherExtensions.cs
+++ b/src/WeihanLi.Common/Aspect/InvocationEnricherExtensions.cs
@@ -5,10 +5,7 @@ public static class InvocationEnricherExtensions
public static void AddProperty(this IInvocation invocation, string propertyName,
object propertyValue, bool overwrite = false)
{
- if (null == invocation)
- {
- throw new ArgumentNullException(nameof(invocation));
- }
+ Guard.NotNull(invocation);
if (!invocation.Properties.ContainsKey(propertyName) || overwrite)
{
@@ -19,10 +16,7 @@ public static void AddProperty(this IInvocation invocation, string propertyName,
public static void AddProperty(this IInvocation invocation, string propertyName,
Func propertyValueFactory, bool overwrite = false)
{
- if (null == invocation)
- {
- throw new ArgumentNullException(nameof(invocation));
- }
+ Guard.NotNull(invocation);
if (!invocation.Properties.ContainsKey(propertyName)
|| overwrite)
diff --git a/src/WeihanLi.Common/Aspect/MethodSignature.cs b/src/WeihanLi.Common/Aspect/MethodSignature.cs
index 816610d8..429329f9 100644
--- a/src/WeihanLi.Common/Aspect/MethodSignature.cs
+++ b/src/WeihanLi.Common/Aspect/MethodSignature.cs
@@ -2,21 +2,15 @@
namespace WeihanLi.Common.Aspect;
-internal sealed class MethodSignature
+internal sealed class MethodSignature(string methodName, IReadOnlyList parameters)
{
- public IReadOnlyList Parameters { get; }
- public string MethodName { get; }
+ public IReadOnlyList Parameters { get; } = parameters;
+ public string MethodName { get; } = methodName;
public MethodSignature(MethodBase method) : this(method.Name, method.GetParameters().Select(p => p.ParameterType).ToArray())
{
}
- public MethodSignature(string methodName, IReadOnlyList parameters)
- {
- Parameters = parameters;
- MethodName = methodName;
- }
-
public override bool Equals(object? obj)
{
// if object is null or type does not match return false...
diff --git a/src/WeihanLi.Common/Aspect/ProxyFactoryExtensions.cs b/src/WeihanLi.Common/Aspect/ProxyFactoryExtensions.cs
index dcefe794..9a77cc23 100644
--- a/src/WeihanLi.Common/Aspect/ProxyFactoryExtensions.cs
+++ b/src/WeihanLi.Common/Aspect/ProxyFactoryExtensions.cs
@@ -111,7 +111,7 @@ public static TService CreateProxyWithTarget(this IProxyFactory proxyF
public static object CreateProxyWithTarget(this IProxyFactory proxyFactory, Type serviceType, object target)
{
- return proxyFactory.CreateProxyWithTarget(serviceType, target, Array.Empty