diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/CommonInitializer/DbContextOptionsBuilderFactory.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/CommonInitializer/DbContextOptionsBuilderFactory.cs" index aacec4d..ef69cff 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/CommonInitializer/DbContextOptionsBuilderFactory.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/CommonInitializer/DbContextOptionsBuilderFactory.cs" @@ -1,13 +1,12 @@ using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; namespace CommonInitializer { public static class DbContextOptionsBuilderFactory { public static DbContextOptionsBuilder Create() - where TDbContext:DbContext - { + where TDbContext : DbContext + { var connStr = Environment.GetEnvironmentVariable("DefaultDB:ConnStr"); var optionsBuilder = new DbContextOptionsBuilder(); //optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=YouzackVNextDB;User ID=sa;Password=dLLikhQWy5TBz1uM;"); diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/CommonInitializer/InitializerOptions.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/CommonInitializer/InitializerOptions.cs" index 53f6dd9..459418a 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/CommonInitializer/InitializerOptions.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/CommonInitializer/InitializerOptions.cs" @@ -4,34 +4,7 @@ public class InitializerOptions { public string LogFilePath { get; set; } - /// - /// 入口项目的一个主要的类,会从这个类所在的程序集为根扫描所有程序进行IModuleInitializer等的遍历 - /// - public Type StartupType { get; set; } - - private string? applicationName; - - /// - /// 应用程序名,默认值是StartupType所在的程序集的名字,可以手动修改。 - /// 这个名字一般用于EventBus等用于标识这个应用,因此要维持“同一个项目值保持一直,不同项目不能冲突” - /// - public string ApplicationName - { - get - { - if (string.IsNullOrEmpty(applicationName)) - { - return StartupType.Assembly.GetName().Name; - } - else - { - return applicationName; - } - } - set - { - this.applicationName = value; - } - } + //用于EventBus的QueueName,因此要维持“同一个项目值保持一直,不同项目不能冲突” + public string EventBusQueueName { get; set; } } } diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/CommonInitializer/WebApplicationBuilderExtensions.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/CommonInitializer/WebApplicationBuilderExtensions.cs" index 400d2ea..0fdc130 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/CommonInitializer/WebApplicationBuilderExtensions.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/CommonInitializer/WebApplicationBuilderExtensions.cs" @@ -34,11 +34,10 @@ public static void ConfigureDbConfiguration(this WebApplicationBuilder builder) public static void ConfigureExtraServices(this WebApplicationBuilder builder, InitializerOptions initOptions) { - var startupType = initOptions.StartupType; - IServiceCollection services = builder.Services; IConfiguration configuration = builder.Configuration; - services.RunModuleInitializers(startupType); + var assemblies = ReflectionHelper.GetAllReferencedAssemblies(); + services.RunModuleInitializers(assemblies); services.AddAllDbContexts(ctx => { //连接字符串如果放到appsettings.json中,会有泄密的风险 @@ -46,7 +45,7 @@ public static void ConfigureExtraServices(this WebApplicationBuilder builder, In //因此这里推荐放到环境变量中。 string connStr = configuration.GetValue("DefaultDB:ConnStr"); ctx.UseSqlServer(connStr); - }, startupType); + }, assemblies); //开始:Authentication,Authorization //只要需要校验Authentication报文头的地方(非IdentityService.WebAPI项目)也需要启用这些 @@ -62,7 +61,7 @@ public static void ConfigureExtraServices(this WebApplicationBuilder builder, In }); //结束:Authentication,Authorization - services.AddMediatR(startupType); + services.AddMediatR(assemblies); //现在不用手动AddMVC了,因此把文档中的services.AddMvc(options =>{})改写成Configure(options=> {})这个问题很多都类似 services.Configure(options => { @@ -94,13 +93,12 @@ public static void ConfigureExtraServices(this WebApplicationBuilder builder, In builder.AddSerilog(); }); services.AddFluentValidation(fv => - { - var asms = ReflectionHelper.GetAllReferencedAssemblies(startupType.Assembly); - fv.RegisterValidatorsFromAssemblies(asms); + { + fv.RegisterValidatorsFromAssemblies(assemblies); }); services.Configure(configuration.GetSection("JWT")); services.Configure(configuration.GetSection("RabbitMQ")); - services.AddEventBus(initOptions.ApplicationName, startupType); + services.AddEventBus(initOptions.EventBusQueueName, assemblies); //Redis的配置 string redisConnStr = configuration.GetValue("Redis:ConnStr"); @@ -108,8 +106,7 @@ public static void ConfigureExtraServices(this WebApplicationBuilder builder, In services.AddSingleton(typeof(IConnectionMultiplexer), redisConnMultiplexer); services.Configure(options => { - options.ForwardedHeaders = - ForwardedHeaders.All; + options.ForwardedHeaders = ForwardedHeaders.All; }); } } diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.Infrastructure/FSRepository.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.Infrastructure/FSRepository.cs" index 04e4723..48f8cbc 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.Infrastructure/FSRepository.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.Infrastructure/FSRepository.cs" @@ -14,7 +14,7 @@ public FSRepository(FSDbContext dbContext) public Task FindFileAsync(long fileSize, string sha256Hash) { - return dbContext.UploadItems.FirstOrDefaultAsync(u => u.FileSizeInBytes == fileSize + return dbContext.UploadItems.FirstOrDefaultAsync(u => u.FileSizeInBytes == fileSize && u.FileSHA256Hash == sha256Hash); } } diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/GlobalUsings.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/GlobalUsings.cs" index b9bb53b..36a6837 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/GlobalUsings.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/GlobalUsings.cs" @@ -1,8 +1,5 @@ global using Microsoft.AspNetCore.Mvc; -global using Microsoft.EntityFrameworkCore; global using System; -global using System.Collections.Generic; global using System.IO; -global using System.Linq; global using System.Threading; global using System.Threading.Tasks; diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/Program.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/Program.cs" index da8f11d..e76215c 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/Program.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/Program.cs" @@ -1,6 +1,5 @@ using CommonInitializer; using FileService.Infrastructure.Services; -using FileService.WebAPI.Uploader; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -10,7 +9,7 @@ builder.ConfigureExtraServices(new InitializerOptions { LogFilePath = "e:/temp/FileService.log", - StartupType = typeof(UploaderController) + EventBusQueueName = "FileService.WebAPI", }); // Add services to the container. diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/Uploader/UploaderController.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/Uploader/UploaderController.cs" index 88bad51..d0417ee 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/Uploader/UploaderController.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/Uploader/UploaderController.cs" @@ -29,7 +29,7 @@ public UploaderController(FSDomainService domainService, FSDbContext dbContext, [HttpGet] public async Task FileExists(long fileSize, string sha256Hash) { - var item = await repository.FindFileAsync(fileSize,sha256Hash); + var item = await repository.FindFileAsync(fileSize, sha256Hash); if (item == null) { return new FileExistsResponse(false, null); diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/wwwroot/2021/11/12/51eb9630bfd4ad6df67f3904a181db53b0ba026d3069ebf3796f77209d4a01b9/b052fac9-7530-4efe-85b2-14a1fa5d85c1.m4a" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/wwwroot/2021/11/12/51eb9630bfd4ad6df67f3904a181db53b0ba026d3069ebf3796f77209d4a01b9/b052fac9-7530-4efe-85b2-14a1fa5d85c1.m4a" new file mode 100644 index 0000000..916b06d Binary files /dev/null and "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/wwwroot/2021/11/12/51eb9630bfd4ad6df67f3904a181db53b0ba026d3069ebf3796f77209d4a01b9/b052fac9-7530-4efe-85b2-14a1fa5d85c1.m4a" differ diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/wwwroot/2021/11/12/cb76081691ff7baff3ffc151a38b40e92f705f8e8398c96ac6b4ef9854e3c5d8/Model Test 6.mp3" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/wwwroot/2021/11/12/cb76081691ff7baff3ffc151a38b40e92f705f8e8398c96ac6b4ef9854e3c5d8/Model Test 6.mp3" new file mode 100644 index 0000000..3dda32d Binary files /dev/null and "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/FileService.WebAPI/wwwroot/2021/11/12/cb76081691ff7baff3ffc151a38b40e92f705f8e8398c96ac6b4ef9854e3c5d8/Model Test 6.mp3" differ diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.Domain/IIdRepository.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.Domain/IIdRepository.cs" index 41c0f74..b501806 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.Domain/IIdRepository.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.Domain/IIdRepository.cs" @@ -75,7 +75,7 @@ public interface IIdRepository /// /// public Task RemoveUserAsync(Guid id); - + /// /// 添加管理员 /// diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.Domain/IdDomainService.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.Domain/IdDomainService.cs" index 94e96dd..33b61eb 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.Domain/IdDomainService.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.Domain/IdDomainService.cs" @@ -12,8 +12,8 @@ public class IdDomainService private readonly ITokenService tokenService; private readonly IOptions optJWT; - public IdDomainService(IIdRepository repository, - ITokenService tokenService,IOptions optJWT) + public IdDomainService(IIdRepository repository, + ITokenService tokenService, IOptions optJWT) { this.repository = repository; this.tokenService = tokenService; @@ -49,7 +49,7 @@ public async Task<(SignInResult Result, string? Token)> LoginByPhoneAndPwdAsync( { var user = await repository.FindByPhoneNumberAsync(phoneNum); string token = await BuildTokenAsync(user); - return (SignInResult.Success,token); + return (SignInResult.Success, token); } else { diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.Infrastructure/IdRepository.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.Infrastructure/IdRepository.cs" index cde8295..3401639 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.Infrastructure/IdRepository.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.Infrastructure/IdRepository.cs" @@ -6,7 +6,7 @@ namespace IdentityService.Infrastructure { - class IdRepository: IIdRepository + class IdRepository : IIdRepository { private readonly IdUserManager userManager; private readonly RoleManager roleManager; diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Controllers/Login/LoginController.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Controllers/Login/LoginController.cs" index cb9a1a9..725a062 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Controllers/Login/LoginController.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Controllers/Login/LoginController.cs" @@ -16,7 +16,7 @@ public class LoginController : ControllerBase private readonly IIdRepository repository; private readonly IdDomainService idService; - public LoginController(IdDomainService idService,IIdRepository repository) + public LoginController(IdDomainService idService, IIdRepository repository) { this.idService = idService; this.repository = repository; @@ -65,7 +65,7 @@ public async Task> GetUserInfo() { //todo:要通过行为验证码、图形验证码等形式来防止暴力破解 (var checkResult, string? token) = await idService.LoginByPhoneAndPwdAsync(req.PhoneNum, req.Password); - if(checkResult.Succeeded) + if (checkResult.Succeeded) { return token; } @@ -85,7 +85,7 @@ public async Task> GetUserInfo() [HttpPost] public async Task> LoginByUserNameAndPwd(LoginByUserNameAndPwdRequest req) { - (var checkResult,var token) = await idService.LoginByUserNameAndPwdAsync(req.UserName, req.Password); + (var checkResult, var token) = await idService.LoginByUserNameAndPwdAsync(req.UserName, req.Password); if (checkResult.Succeeded) { return token!; diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Controllers/UserAdmin/UserAdminController.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Controllers/UserAdmin/UserAdminController.cs" index 7a22049..f68a797 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Controllers/UserAdmin/UserAdminController.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Controllers/UserAdmin/UserAdminController.cs" @@ -45,7 +45,7 @@ public async Task FindById(Guid id) [HttpPost] public async Task AddAdminUser(AddAdminUserRequest req) { - (var result,var user,var password) = await repository + (var result, var user, var password) = await repository .AddAdminUserAsync(req.UserName, req.PhoneNum); if (!result.Succeeded) { diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Events/UserCreatedEventHandler.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Events/UserCreatedEventHandler.cs" index 082b95f..184ab4d 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Events/UserCreatedEventHandler.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Events/UserCreatedEventHandler.cs" @@ -1,5 +1,4 @@ using Identity.Repository; -using Microsoft.Extensions.Logging; using Zack.EventBus; namespace IdentityService.WebAPI.Events diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/GlobalUsings.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/GlobalUsings.cs" index 355263b..e237cba 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/GlobalUsings.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/GlobalUsings.cs" @@ -1,3 +1,2 @@ global using System; -global using System.Collections.Generic; global using System.Threading.Tasks; diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Program.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Program.cs" index a02b408..fe6132e 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Program.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Program.cs" @@ -3,7 +3,6 @@ using IdentityService.Domain; using IdentityService.Infrastructure; using IdentityService.Infrastructure.Services; -using IdentityService.WebAPI.Controllers.Login; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; @@ -13,7 +12,11 @@ // Add services to the container. builder.ConfigureDbConfiguration(); -builder.ConfigureExtraServices(new InitializerOptions { StartupType = typeof(LoginController), LogFilePath = "e:/temp/IdentityService.log" }); +builder.ConfigureExtraServices(new InitializerOptions +{ + EventBusQueueName = "IdentityService.WebAPI", + LogFilePath = "e:/temp/IdentityService.log" +}); builder.Services.AddControllers(); builder.Services.AddSwaggerGen(c => { diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Properties/launchSettings.json" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Properties/launchSettings.json" index 0777ca9..08081bf 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Properties/launchSettings.json" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/IdentityService.WebAPI/Properties/launchSettings.json" @@ -4,8 +4,8 @@ "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { - "applicationUrl": "http://localhost:61250", - "sslPort": 44392 + "applicationUrl": "http://localhost:6802/", + "sslPort": 44395 } }, "profiles": { diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Albums/AlbumController.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Albums/AlbumController.cs" index 933a7df..ae488ee 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Albums/AlbumController.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Albums/AlbumController.cs" @@ -36,7 +36,7 @@ public Task FindByCategoryId([RequiredGuid] Guid categoryId) [HttpPost] public async Task> Add(AlbumAddRequest req) { - Album album = await domainService.AddAlbumAsync(req.CategoryId,req.Name); + Album album = await domainService.AddAlbumAsync(req.CategoryId, req.Name); dbCtx.Add(album); return album.Id; } @@ -46,7 +46,7 @@ public async Task> Add(AlbumAddRequest req) public async Task Update([RequiredGuid] Guid id, AlbumUpdateRequest request) { var album = await repository.GetAlbumByIdAsync(id); - if(album==null) + if (album == null) { return NotFound("id没找到"); } diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Categories/CategoryController.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Categories/CategoryController.cs" index 4424ae4..a1da563 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Categories/CategoryController.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Categories/CategoryController.cs" @@ -53,7 +53,7 @@ public async Task> Add(CategoryAddRequest req) public async Task Update([RequiredGuid] Guid id, CategoryUpdateRequest request) { var cat = await repository.GetCategoryByIdAsync(id); - if(cat==null) + if (cat == null) { return NotFound("id不存在"); } diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Episodes/EpisodeController.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Episodes/EpisodeController.cs" index 2e4b26c..0c91511 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Episodes/EpisodeController.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Episodes/EpisodeController.cs" @@ -30,8 +30,8 @@ public async Task> Add(EpisodeAddRequest req) //如果上传的是m4a,不用转码,直接存到数据库 if (req.AudioUrl.ToString().EndsWith("m4a", StringComparison.OrdinalIgnoreCase)) { - Episode episode = await domainService.AddEpisodeAsync(req.Name,req.AlbumId, - req.AudioUrl,req.DurationInSecond,req.SubtitleType,req.Subtitle); + Episode episode = await domainService.AddEpisodeAsync(req.Name, req.AlbumId, + req.AudioUrl, req.DurationInSecond, req.SubtitleType, req.Subtitle); dbContext.Add(episode); return episode.Id; } @@ -54,7 +54,7 @@ public async Task> Add(EpisodeAddRequest req) public async Task Update([RequiredGuid] Guid id, EpisodeUpdateRequest request) { var episode = await repository.GetEpisodeByIdAsync(id); - if(episode==null) + if (episode == null) { return NotFound("id没找到"); } diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/EventHandlers/MediaEncodingStatusChangeIntegrationHandler.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/EventHandlers/MediaEncodingStatusChangeIntegrationHandler.cs" index 412c301..010e63a 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/EventHandlers/MediaEncodingStatusChangeIntegrationHandler.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/EventHandlers/MediaEncodingStatusChangeIntegrationHandler.cs" @@ -15,7 +15,7 @@ class MediaEncodingStatusChangeIntegrationHandler : DynamicIntegrationEventHandl private readonly EncodingEpisodeHelper encHelper; private readonly IHubContext hubContext; - public MediaEncodingStatusChangeIntegrationHandler(ListeningDbContext dbContext, + public MediaEncodingStatusChangeIntegrationHandler(ListeningDbContext dbContext, EncodingEpisodeHelper encHelper, IHubContext hubContext, IListeningRepository repository) { @@ -60,7 +60,7 @@ public override async Task HandleDynamic(string eventName, dynamic eventData) Episode episode = Episode.Create(id, maxSeq.Value + 1, encodingEpisode.Name, albumId, outputUrl, encodingEpisode.DurationInSecond, encodingEpisode.SubtitleType, encodingEpisode.Subtitle);*/ var builder = new Episode.Builder(); - builder.Id(id).SequenceNumber(maxSeq+1).Name(encItem.Name) + builder.Id(id).SequenceNumber(maxSeq + 1).Name(encItem.Name) .AlbumId(albumId).AudioUrl(outputUrl) .DurationInSecond(encItem.DurationInSecond) .SubtitleType(encItem.SubtitleType).Subtitle(encItem.Subtitle); diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Program.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Program.cs" index 9e8a5a6..62f087c 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Program.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Admin.WebAPI/Program.cs" @@ -1,5 +1,4 @@ using CommonInitializer; -using Listening.Admin.WebAPI.Albums; using Listening.Admin.WebAPI.Hubs; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; @@ -10,7 +9,7 @@ builder.ConfigureExtraServices(new InitializerOptions { LogFilePath = "e:/temp/Listening.Admin.log", - StartupType = typeof(AlbumController) + EventBusQueueName = "Listening.Admin" }); builder.Services.AddScoped(); builder.Services.AddControllers(); diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Domain/Entities/Episode.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Domain/Entities/Episode.cs" index a9a3670..bbdd186 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Domain/Entities/Episode.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Domain/Entities/Episode.cs" @@ -162,11 +162,11 @@ public Builder SubtitleType(string value) } public Episode Build() { - if(id==Guid.Empty) + if (id == Guid.Empty) { throw new ArgumentOutOfRangeException(nameof(id)); } - if (name==null) + if (name == null) { throw new ArgumentNullException(nameof(name)); } @@ -178,7 +178,7 @@ public Episode Build() { throw new ArgumentNullException(nameof(audioUrl)); } - if(durationInSecond<=0) + if (durationInSecond <= 0) { throw new ArgumentOutOfRangeException(nameof(durationInSecond)); } diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Domain/ListeningDomainService.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Domain/ListeningDomainService.cs" index ea9bcb1..bceeff2 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Domain/ListeningDomainService.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Domain/ListeningDomainService.cs" @@ -17,10 +17,10 @@ public async Task AddAlbumAsync(Guid categoryId, MultilingualString name) { int maxSeq = await repository.GetMaxSeqOfAlbumsAsync(categoryId); var id = Guid.NewGuid(); - return Album.Create(id, maxSeq+1, name,categoryId); + return Album.Create(id, maxSeq + 1, name, categoryId); } - public async Task SortAlbumsAsync(Guid categoryId,Guid[] sortedAlbumIds) + public async Task SortAlbumsAsync(Guid categoryId, Guid[] sortedAlbumIds) { var albums = await repository.GetAlbumsByCategoryIdAsync(categoryId); var idsInDB = albums.Select(a => a.Id); @@ -43,7 +43,7 @@ public async Task SortAlbumsAsync(Guid categoryId,Guid[] sortedAlbumIds) } } - public async Task AddCategoryAsync(MultilingualString name,Uri coverUrl) + public async Task AddCategoryAsync(MultilingualString name, Uri coverUrl) { int maxSeq = await repository.GetMaxSeqOfCategoriesAsync(); var id = Guid.NewGuid(); @@ -73,7 +73,7 @@ public async Task SortCategoriesAsync(Guid[] sortedCategoryIds) } public async Task AddEpisodeAsync(MultilingualString name, - Guid albumId, Uri audioUrl,double durationInSecond, + Guid albumId, Uri audioUrl, double durationInSecond, string subtitleType, string subtitle) { int maxSeq = await repository.GetMaxSeqOfEpisodesAsync(albumId); diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Infrastructure/ListeningRepository.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Infrastructure/ListeningRepository.cs" index e3d9e8a..ca5c125 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Infrastructure/ListeningRepository.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Infrastructure/ListeningRepository.cs" @@ -53,7 +53,7 @@ public async Task GetMaxSeqOfCategoriesAsync() public async Task GetEpisodeByIdAsync(Guid episodeId) { - return await dbCtx.Episodes.SingleOrDefaultAsync(e=>e.Id== episodeId); + return await dbCtx.Episodes.SingleOrDefaultAsync(e => e.Id == episodeId); } public async Task GetMaxSeqOfEpisodesAsync(Guid albumId) @@ -65,7 +65,7 @@ public async Task GetMaxSeqOfEpisodesAsync(Guid albumId) public Task GetEpisodesByAlbumIdAsync(Guid albumId) { - return dbCtx.Episodes.OrderBy(e=>e.SequenceNumber).Where(a => a.AlbumId == albumId).ToArrayAsync(); + return dbCtx.Episodes.OrderBy(e => e.SequenceNumber).Where(a => a.AlbumId == albumId).ToArrayAsync(); } } } diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Main.WebAPI/Controllers/Episodes/ViewModels/EpisodeVM.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Main.WebAPI/Controllers/Episodes/ViewModels/EpisodeVM.cs" index 4992127..bb59c67 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Main.WebAPI/Controllers/Episodes/ViewModels/EpisodeVM.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Main.WebAPI/Controllers/Episodes/ViewModels/EpisodeVM.cs" @@ -18,7 +18,7 @@ public record EpisodeVM(Guid Id, MultilingualString Name, Guid AlbumId, Uri Audi { SentenceVM vm = new SentenceVM(s.StartTime.TotalSeconds, s.EndTime.TotalSeconds, s.Value); sentenceVMs.Add(vm); - } + } } return new EpisodeVM(e.Id, e.Name, e.AlbumId, e.AudioUrl, e.DurationInSecond, sentenceVMs); } diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Main.WebAPI/GlobalUsings.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Main.WebAPI/GlobalUsings.cs" index f1bf84e..1427a39 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Main.WebAPI/GlobalUsings.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Main.WebAPI/GlobalUsings.cs" @@ -1,7 +1,6 @@ global using Listening.Domain; global using Listening.Domain.Entities; global using Microsoft.AspNetCore.Mvc; -global using Microsoft.EntityFrameworkCore; global using System; global using System.Collections.Generic; global using System.ComponentModel.DataAnnotations; diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Main.WebAPI/Program.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Main.WebAPI/Program.cs" index 01beab4..f40171b 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Main.WebAPI/Program.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Listening.Main.WebAPI/Program.cs" @@ -1,5 +1,4 @@ using CommonInitializer; -using Listening.Main.WebAPI.Controllers.Albums.ViewModels; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -9,7 +8,7 @@ builder.ConfigureExtraServices(new InitializerOptions { LogFilePath = "e:/temp/Listening.Main.log", - StartupType = typeof(AlbumVM) + EventBusQueueName = "Listening.Main" }); // Add services to the container. //builder.Services.AddScoped(); diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/MediaEncoder.WebAPI/BgServices/EncodingBgService.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/MediaEncoder.WebAPI/BgServices/EncodingBgService.cs" index f2dbfcb..12a0791 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/MediaEncoder.WebAPI/BgServices/EncodingBgService.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/MediaEncoder.WebAPI/BgServices/EncodingBgService.cs" @@ -56,12 +56,12 @@ public EncodingBgService(IServiceScopeFactory spf) /// /// /// ok表示是否下载成功,sourceFile为保存成功的本地文件 - private async Task<(bool ok,FileInfo sourceFile)> DownloadSrcAsync(EncodingItem encItem, CancellationToken ct) + private async Task<(bool ok, FileInfo sourceFile)> DownloadSrcAsync(EncodingItem encItem, CancellationToken ct) { //开始下载源文件 string tempDir = Path.Combine(Path.GetTempPath(), "MediaEncodingDir"); //源文件的临时保存路径 - string sourceFullPath = Path.Combine(tempDir, Guid.NewGuid() + "." + string sourceFullPath = Path.Combine(tempDir, Guid.NewGuid() + "." + Path.GetExtension(encItem.Name)); FileInfo sourceFile = new FileInfo(sourceFullPath); Guid id = encItem.Id; @@ -73,7 +73,7 @@ private async Task<(bool ok,FileInfo sourceFile)> DownloadSrcAsync(EncodingItem { logger.LogInterpolatedWarning($"下载Id={id},Url={encItem.SourceUrl}失败,{statusCode}"); sourceFile.Delete(); - return(false, sourceFile); + return (false, sourceFile); } else { @@ -89,8 +89,8 @@ private async Task<(bool ok,FileInfo sourceFile)> DownloadSrcAsync(EncodingItem private Task UploadFileAsync(FileInfo file, CancellationToken ct) { Uri urlRoot = optionFileService.Value.UrlRoot; - FileServiceClient fileService = new FileServiceClient(httpClientFactory, - urlRoot,optionJWT.Value, tokenService); + FileServiceClient fileService = new FileServiceClient(httpClientFactory, + urlRoot, optionJWT.Value, tokenService); return fileService.UploadAsync(file, ct); } @@ -128,7 +128,7 @@ private static string ComputeSha256Hash(FileInfo file) /// /// /// 转码结果 - private async Task EncodeAsync(FileInfo srcFile,FileInfo destFile, + private async Task EncodeAsync(FileInfo srcFile, FileInfo destFile, string outputFormat, CancellationToken ct) { var encoder = encoderFactory.Create(outputFormat); @@ -165,13 +165,13 @@ private async Task ProcessItemAsync(EncodingItem encItem, CancellationToken ct) } encItem.Start(); await dbContext.SaveChangesAsync(ct);//立即保存一下状态的修改 - //发出一次集成事件 + //发出一次集成事件 (var downloadOk, var srcFile) = await DownloadSrcAsync(encItem, ct); if (!downloadOk) { encItem.Fail($"下载失败"); return; - } + } FileInfo destFile = BuildDestFile(encItem); try { diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/MediaEncoder.WebAPI/GlobalUsings.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/MediaEncoder.WebAPI/GlobalUsings.cs" index 64a25d4..80f3931 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/MediaEncoder.WebAPI/GlobalUsings.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/MediaEncoder.WebAPI/GlobalUsings.cs" @@ -1,5 +1,4 @@ global using MediatR; -global using Microsoft.AspNetCore.Mvc; global using Microsoft.EntityFrameworkCore; global using System; global using System.Collections.Generic; diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/MediaEncoder.WebAPI/Program.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/MediaEncoder.WebAPI/Program.cs" index 0683a25..2ba5068 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/MediaEncoder.WebAPI/Program.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/MediaEncoder.WebAPI/Program.cs" @@ -12,7 +12,7 @@ builder.ConfigureExtraServices(new InitializerOptions { LogFilePath = "e:/temp/MediaEncoder.log", - StartupType = typeof(EncodingBgService) + EventBusQueueName = "MediaEncoder.WebAPI" }); builder.Services.Configure(builder.Configuration.GetSection("FileService:Endpoint")); builder.Services.Configure(builder.Configuration.GetSection("JWT")); diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/SearchService.WebAPI/Program.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/SearchService.WebAPI/Program.cs" index 9b75d3f..f6438e9 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/SearchService.WebAPI/Program.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/SearchService.WebAPI/Program.cs" @@ -4,7 +4,6 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Nest; -using SearchService.WebAPI.Controllers; using SearchService.WebAPI.Options; var builder = WebApplication.CreateBuilder(args); @@ -12,7 +11,7 @@ builder.ConfigureExtraServices(new InitializerOptions { LogFilePath = "e:/temp/SearchService.log", - StartupType = typeof(SearchController) + EventBusQueueName = "SearchService.WebAPI" }); // Add services to the container. diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.ASPNETCore/MemoryCacheHelper.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.ASPNETCore/MemoryCacheHelper.cs" index 70c3b39..84587a8 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.ASPNETCore/MemoryCacheHelper.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.ASPNETCore/MemoryCacheHelper.cs" @@ -36,14 +36,14 @@ private static void ValidateValueType() } private static void InitCacheEntry(ICacheEntry entry, int baseExpireSeconds) - { + { //过期时间.Random.Shared 是.NET6新增的 - double sec = Random.Shared.Next(baseExpireSeconds,baseExpireSeconds*2); + double sec = Random.Shared.Next(baseExpireSeconds, baseExpireSeconds * 2); TimeSpan expiration = TimeSpan.FromSeconds(sec); entry.AbsoluteExpirationRelativeToNow = expiration; } - public TResult? GetOrCreate(string cacheKey, Func valueFactory, int baseExpireSeconds = 60) + public TResult? GetOrCreate(string cacheKey, Func valueFactory, int baseExpireSeconds = 60) { ValidateValueType(); //因为IMemoryCache保存的是一个CacheEntry,所以null值也认为是合法的,因此返回null不会有“缓存穿透”的问题 diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.ASPNETCore/UnitOfWorkFilter.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.ASPNETCore/UnitOfWorkFilter.cs" index 82da10e..7a60714 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.ASPNETCore/UnitOfWorkFilter.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.ASPNETCore/UnitOfWorkFilter.cs" @@ -3,64 +3,63 @@ using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using System.Transactions; namespace Zack.ASPNETCore; -public class UnitOfWorkFilter: IAsyncActionFilter +public class UnitOfWorkFilter : IAsyncActionFilter { - private static UnitOfWorkAttribute? GetUoWAttr(ActionDescriptor actionDesc) - { - var caDesc = actionDesc as ControllerActionDescriptor; - if(caDesc==null) - { - return null; - } - //try to get UnitOfWorkAttribute from controller, - //if there is no UnitOfWorkAttribute on controller, - //try to get UnitOfWorkAttribute from action - var uowAttr = caDesc.ControllerTypeInfo - .GetCustomAttribute(); - if(uowAttr != null) - { - return uowAttr; - } - else - { - return caDesc.MethodInfo - .GetCustomAttribute(); - } - } - public async Task OnActionExecutionAsync(ActionExecutingContext context, - ActionExecutionDelegate next) - { - var uowAttr = GetUoWAttr(context.ActionDescriptor); - if (uowAttr == null) - { - await next(); - return; - } - using TransactionScope txScope = new(TransactionScopeAsyncFlowOption.Enabled); - List dbCtxs = new List(); - foreach (var dbCtxType in uowAttr.DbContextTypes) - { - //用HttpContext的RequestServices - //确保获取的是和请求相关的Scope实例 - var sp = context.HttpContext.RequestServices; - DbContext dbCtx = (DbContext)sp.GetRequiredService(dbCtxType); - dbCtxs.Add(dbCtx); - } - var result = await next(); - if (result.Exception == null) - { - foreach (var dbCtx in dbCtxs) - { - await dbCtx.SaveChangesAsync(); - } - txScope.Complete(); - } - } + private static UnitOfWorkAttribute? GetUoWAttr(ActionDescriptor actionDesc) + { + var caDesc = actionDesc as ControllerActionDescriptor; + if (caDesc == null) + { + return null; + } + //try to get UnitOfWorkAttribute from controller, + //if there is no UnitOfWorkAttribute on controller, + //try to get UnitOfWorkAttribute from action + var uowAttr = caDesc.ControllerTypeInfo + .GetCustomAttribute(); + if (uowAttr != null) + { + return uowAttr; + } + else + { + return caDesc.MethodInfo + .GetCustomAttribute(); + } + } + public async Task OnActionExecutionAsync(ActionExecutingContext context, + ActionExecutionDelegate next) + { + var uowAttr = GetUoWAttr(context.ActionDescriptor); + if (uowAttr == null) + { + await next(); + return; + } + using TransactionScope txScope = new(TransactionScopeAsyncFlowOption.Enabled); + List dbCtxs = new List(); + foreach (var dbCtxType in uowAttr.DbContextTypes) + { + //用HttpContext的RequestServices + //确保获取的是和请求相关的Scope实例 + var sp = context.HttpContext.RequestServices; + DbContext dbCtx = (DbContext)sp.GetRequiredService(dbCtxType); + dbCtxs.Add(dbCtx); + } + var result = await next(); + if (result.Exception == null) + { + foreach (var dbCtx in dbCtxs) + { + await dbCtx.SaveChangesAsync(); + } + txScope.Complete(); + } + } } \ No newline at end of file diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Commons/ModuleInitializerExtensions.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Commons/ModuleInitializerExtensions.cs" index 747345a..4e1e703 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Commons/ModuleInitializerExtensions.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Commons/ModuleInitializerExtensions.cs" @@ -8,22 +8,6 @@ namespace Zack.Commons { public static class ModuleInitializerExtensions { - public static IServiceCollection RunModuleInitializers(this IServiceCollection services, Type rootType) - { - return RunModuleInitializers(services, rootType.Assembly); - } - /// - /// 运行rootAssembly及直接或者间接引用的程序集(排除系统程序集)中的IModuleInitializer - /// - /// - /// - /// - public static IServiceCollection RunModuleInitializers(this IServiceCollection services, Assembly rootAssembly) - { - var asms = ReflectionHelper.GetAllReferencedAssemblies(rootAssembly); - return RunModuleInitializers(services, asms); - } - /// /// 每个项目中都可以自己写一些实现了IModuleInitializer接口的类,在其中注册自己需要的服务,这样避免所有内容到入口项目中注册 /// @@ -35,9 +19,9 @@ public static IServiceCollection RunModuleInitializers(this IServiceCollection s .Where(t => !t.IsAbstract && typeof(IModuleInitializer).IsAssignableFrom(t))) { IModuleInitializer? initializer = (IModuleInitializer?)Activator.CreateInstance(implType); - if(initializer == null) + if (initializer == null) { - throw new ApplicationException("Cannot create an instance of"+implType); + throw new ApplicationException("Cannot create an instance of" + implType); } initializer.Initialize(services); } diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Commons/ReflectionHelper.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Commons/ReflectionHelper.cs" index cae56a7..19db4a9 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Commons/ReflectionHelper.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Commons/ReflectionHelper.cs" @@ -4,105 +4,130 @@ using System.IO; using System.Linq; using System.Reflection; +using System.Reflection.PortableExecutable; -namespace Zack.Commons +namespace Zack.Commons; +public static class ReflectionHelper { - public static class ReflectionHelper + //是否是微软等的官方Assembly + private static bool IsSystemAssembly(Assembly asm) { - //是否是微软等的官方Assembly - private static bool IsSystemAssembly(Assembly asm) + var asmCompanyAttr = asm.GetCustomAttribute(); + if (asmCompanyAttr == null) { - var asmCompanyAttr = asm.GetCustomAttribute(); - if (asmCompanyAttr == null) - { - return false; - } - else - { - string companyName = asmCompanyAttr.Company; - return companyName.Contains("Microsoft Corporation"); - } + return false; + } + else + { + string companyName = asmCompanyAttr.Company; + return companyName.Contains("Microsoft"); } + } + + private static bool IsManagedAssembly(string file) + { + using var fs = File.OpenRead(file); + using PEReader peReader = new PEReader(fs); + var peHeaders = peReader.PEHeaders; + return peHeaders.CorHeader != null; + /* + using var fs1 = File.OpenRead(@"E:\主同步盘\我的坚果云\个人资料\写书\Net Core书稿\随书代码\最后大项目代码\YouZack-VNext\Listening.Admin.WebAPI\bin\Debug\net6.0\runtimes\win-arm\native\Microsoft.Data.SqlClient.SNI.dll"); + using PEReader peReader1 = new PEReader(fs1); + var peHeaders1 = peReader1.PEHeaders; + using var fs2 = File.OpenRead(@"E:\主同步盘\我的坚果云\个人资料\写书\Net Core书稿\随书代码\最后大项目代码\YouZack-VNext\Listening.Admin.WebAPI\bin\Debug\net6.0\System.Data.SqlClient.dll"); + using PEReader peReader2 = new PEReader(fs2); + var peHeaders2 = peReader2.PEHeaders; + string s1 = peHeaders1.ToJsonString(); + string s2 = peHeaders2.ToJsonString();*/ + //return true; + } - /// - /// loop through all assemblies + /// + /// loop through all assemblies + /// + /// + public static IEnumerable GetAllReferencedAssemblies(bool skipSystemAssemblies = true) + { /// 对于MSTest项目启动,Assembly.GetEntryAssembly()是"TestHost",而"TestHost"的GetReferencedAssemblies /// 不包含项目的Dll,可能是因为"TestHost"都是通过Http调用被测试的程序集导致的,因此必须传入一个跟rootAssembly /// https://dotnetcoretutorials.com/2020/07/03/getting-assemblies-is-harder-than-you-think-in-c/ - /// - /// - public static IEnumerable GetAllReferencedAssemblies(Assembly rootAssembly, bool skipSystemAssemblies = true) + Assembly? rootAssembly = Assembly.GetEntryAssembly(); + if (rootAssembly == null) + { + rootAssembly = Assembly.GetCallingAssembly(); + } + var returnAssemblies = new HashSet(new AssemblyEquality()); + var loadedAssemblies = new HashSet(); + var assembliesToCheck = new Queue(); + assembliesToCheck.Enqueue(rootAssembly); + if (skipSystemAssemblies && IsSystemAssembly(rootAssembly) != false) { - if (skipSystemAssemblies && IsSystemAssembly(rootAssembly)) - { - throw new ArgumentOutOfRangeException(nameof(rootAssembly), "rootAssembly cannot be system-level assembly"); - } - var returnAssemblies = new HashSet(new AssemblyEquality()); - var loadedAssemblies = new HashSet(); - var assembliesToCheck = new Queue(); - - assembliesToCheck.Enqueue(rootAssembly); returnAssemblies.Add(rootAssembly); - - while (assembliesToCheck.Any()) + } + while (assembliesToCheck.Any()) + { + var assemblyToCheck = assembliesToCheck.Dequeue(); + foreach (var reference in assemblyToCheck.GetReferencedAssemblies()) { - var assemblyToCheck = assembliesToCheck.Dequeue(); - - foreach (var reference in assemblyToCheck.GetReferencedAssemblies()) + if (!loadedAssemblies.Contains(reference.FullName)) { - if (!loadedAssemblies.Contains(reference.FullName)) + var assembly = Assembly.Load(reference); + if (skipSystemAssemblies && IsSystemAssembly(assembly)) { - var assembly = Assembly.Load(reference); - if (skipSystemAssemblies && IsSystemAssembly(assembly)) - { - continue; - } - assembliesToCheck.Enqueue(assembly); - loadedAssemblies.Add(reference.FullName); - returnAssemblies.Add(assembly); + continue; } + assembliesToCheck.Enqueue(assembly); + loadedAssemblies.Add(reference.FullName); + returnAssemblies.Add(assembly); } } - //如果一个程序集被引用了,但是我们没有直接用在代码中静态使用其中的类, - //而是使用反射的形式使用了那些类, - //那么我们是无法用GetReferencedAssemblies获得这个程序集的 - //因此这里通过扫描运行目录下的dll的形式再去补偿获取一些之前可能没扫描的程序集, - //当然,在项目【发布】的时候,可能已经没有静态引用的程序集就没有被生成, - //因此,如果遇到这种情况,就需要我们在代码中显式的静态引用那个程序集中的一个类了。 - var asmsInBaseDir = Directory.EnumerateFiles(AppContext.BaseDirectory, - "*.dll", new EnumerationOptions { RecurseSubdirectories = true }); - foreach (var asmPath in asmsInBaseDir) - { - Assembly asm; - try - { - asm = Assembly.LoadFile(asmPath); - } - catch (BadImageFormatException) - { - continue; - } - if (skipSystemAssemblies && IsSystemAssembly(asm)) - { - continue; - } - returnAssemblies.Add(asm); - } - return returnAssemblies.ToArray(); } - class AssemblyEquality : EqualityComparer + //以下代码解决两个问题: + //1、如果一个程序集被引用了,但是我们没有直接用在代码中静态使用其中的类, + //而是使用反射的形式使用了那些类, + //那么我们是无法用GetReferencedAssemblies获得这个程序集的 + //2、以MsTest运行的时候GetEntryAssembly()拿到的是TestHost,从而无法进一步的获取它引用的程序集。 + //"TestHost"的GetReferencedAssemblies不包含项目的Dll,可能是因为"TestHost" + //都是通过Http调用被测试的程序集导致的。 + //https://dotnetcoretutorials.com/2020/07/03/getting-assemblies-is-harder-than-you-think-in-c/ + //因此这里通过扫描运行目录下的dll的形式再去补偿获取一些之前可能没扫描的程序集, + //当然,在项目【发布】的时候,可能已经没有静态引用的程序集就没有被生成, + //因此,如果遇到这种情况,就需要我们在代码中显式的静态引用那个程序集中的一个类了。 + var asmsInBaseDir = Directory.EnumerateFiles(AppContext.BaseDirectory, + "*.dll", new EnumerationOptions { RecurseSubdirectories = true }); + foreach (var asmPath in asmsInBaseDir) { - public override bool Equals(Assembly? x, Assembly? y) + if(!IsManagedAssembly(asmPath)) { - if (x == null && y == null) return true; - if (x == null || y == null) return false; - return AssemblyName.ReferenceMatchesDefinition(x.GetName(), y.GetName()); + continue; } - - public override int GetHashCode([DisallowNull] Assembly obj) + AssemblyName asmName = AssemblyName.GetAssemblyName(asmPath); + //如果程序集已经加载过了就不再加载 + if(returnAssemblies.Any(x=>AssemblyName.ReferenceMatchesDefinition(x.GetName(),asmName))) { - return obj.GetName().FullName.GetHashCode(); + continue; } + Assembly asm = Assembly.Load(asmName); + if (skipSystemAssemblies && IsSystemAssembly(asm)) + { + continue; + } + returnAssemblies.Add(asm); + } + return returnAssemblies.ToArray(); + } + class AssemblyEquality : EqualityComparer + { + public override bool Equals(Assembly? x, Assembly? y) + { + if (x == null && y == null) return true; + if (x == null || y == null) return false; + return AssemblyName.ReferenceMatchesDefinition(x.GetName(), y.GetName()); + } + + public override int GetHashCode([DisallowNull] Assembly obj) + { + return obj.GetName().FullName.GetHashCode(); } } -} +} \ No newline at end of file diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.DomainCommons/Models/BaseEntity.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.DomainCommons/Models/BaseEntity.cs" index 5e2f75d..51e47c9 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.DomainCommons/Models/BaseEntity.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.DomainCommons/Models/BaseEntity.cs" @@ -13,7 +13,7 @@ public class BaseEntity : IEntity, IDomainEvents = new List();*/ //好像在.NET 5中,这个DomainEvents必须为public 属性+[NotMapped],因为ChangeTracker跟踪的是一个拷贝,而不是本来这个对象 //但是好像到了.NET6中,DomainEvents为字段也可以了 - private List domainEvents=new(); + private List domainEvents = new(); public Guid Id { get; protected set; } = Guid.NewGuid(); diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.DomainCommons/Models/IAggregateRoot.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.DomainCommons/Models/IAggregateRoot.cs" index 663c7df..28f7118 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.DomainCommons/Models/IAggregateRoot.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.DomainCommons/Models/IAggregateRoot.cs" @@ -1,11 +1,7 @@ -using MediatR; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; - -namespace Zack.DomainCommons.Models +namespace Zack.DomainCommons.Models { public interface IAggregateRoot { - + } } diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.EventBus/RabbitMQEventBus.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.EventBus/RabbitMQEventBus.cs" index a0c0b97..d79520c 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.EventBus/RabbitMQEventBus.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.EventBus/RabbitMQEventBus.cs" @@ -214,7 +214,7 @@ private async Task ProcessEvent(string eventName, string message) { //各自在不同的Scope中,避免DbContext等的共享造成如下问题: //The instance of entity type cannot be tracked because another instance - using var scope = this._serviceProvider.CreateScope(); + using var scope = this._serviceProvider.CreateScope(); IIntegrationEventHandler? handler = scope.ServiceProvider.GetService(subscription) as IIntegrationEventHandler; if (handler == null) { diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.EventBus/ServicesCollectionExtensions.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.EventBus/ServicesCollectionExtensions.cs" index eee6148..9b67b78 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.EventBus/ServicesCollectionExtensions.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.EventBus/ServicesCollectionExtensions.cs" @@ -5,24 +5,14 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using Zack.Commons; namespace Zack.EventBus { public static class ServicesCollectionExtensions { - public static IServiceCollection AddEventBus(this IServiceCollection services, string queueName, Type rootType) - { - var asms = ReflectionHelper.GetAllReferencedAssemblies(rootType.Assembly); - return AddEventBus(services, queueName, asms); - } - - public static IServiceCollection AddEventBus(this IServiceCollection services, string queueName, params Assembly[] assemblies) - { - return AddEventBus(services, queueName, assemblies.ToList()); - } - public static IServiceCollection AddEventBus(this IServiceCollection services, string queueName, IEnumerable assemblies) + public static IServiceCollection AddEventBus(this IServiceCollection services, string queueName, + IEnumerable assemblies) { List eventHandlers = new List(); foreach (var asm in assemblies) diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Infrastructure/EFCore/EFCoreInitializerHelper.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Infrastructure/EFCore/EFCoreInitializerHelper.cs" index 8a85cc8..0a6dd38 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Infrastructure/EFCore/EFCoreInitializerHelper.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Infrastructure/EFCore/EFCoreInitializerHelper.cs" @@ -9,31 +9,14 @@ namespace Microsoft.EntityFrameworkCore { public static class EFCoreInitializerHelper { - /// - /// 把roorType所在的程序集以及直接或者间接引用的程序集中的所有的DbContext都注册到DI中 - /// - /// - /// - /// - /// - public static IServiceCollection AddAllDbContexts(this IServiceCollection services, Action builder, Type startupType) - { - return AddAllDbContexts(services, builder, startupType.Assembly); - } - - public static IServiceCollection AddAllDbContexts(this IServiceCollection services, Action builder, Assembly startupAssembly) - { - var asms = ReflectionHelper.GetAllReferencedAssemblies(startupAssembly); - return AddAllDbContexts(services, builder, asms); - } - /// /// 自动为所有的DbContext注册连接配置 /// /// /// /// - public static IServiceCollection AddAllDbContexts(this IServiceCollection services, Action builder, IEnumerable assemblies) + public static IServiceCollection AddAllDbContexts(this IServiceCollection services, Action builder, + IEnumerable assemblies) { //AddDbContextPool不支持DbContext注入其他对象,而且使用不当有内存暴涨的问题,因此不用AddDbContextPool Type[] types = new Type[] { typeof(IServiceCollection), typeof(Action), typeof(ServiceLifetime), typeof(ServiceLifetime) }; diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Infrastructure/EFCore/ExpressionHelper.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Infrastructure/EFCore/ExpressionHelper.cs" index 6a623bb..1e01b1f 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Infrastructure/EFCore/ExpressionHelper.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Infrastructure/EFCore/ExpressionHelper.cs" @@ -16,51 +16,51 @@ public class ExpressionHelper /// /// public static Expression> MakeEqual(Expression> propAccessor, TProp? other) - where TItem:class - where TProp:class + where TItem : class + where TProp : class { - var e1 = propAccessor.Parameters.Single();//提取出来参数 - BinaryExpression? conditionalExpr = null; - foreach (var prop in typeof(TProp).GetProperties()) + var e1 = propAccessor.Parameters.Single();//提取出来参数 + BinaryExpression? conditionalExpr = null; + foreach (var prop in typeof(TProp).GetProperties()) + { + BinaryExpression equalExpr; + //other的prop属性的值 + object? otherValue = null; + if (other != null) { - BinaryExpression equalExpr; - //other的prop属性的值 - object? otherValue = null; - if (other != null) - { - otherValue = prop.GetValue(other); - } - Type propType = prop.PropertyType; - //访问待比较的属性 - var leftExpr = MakeMemberAccess( - propAccessor.Body,//要取出来Body部分,不能带参数 - prop + otherValue = prop.GetValue(other); + } + Type propType = prop.PropertyType; + //访问待比较的属性 + var leftExpr = MakeMemberAccess( + propAccessor.Body,//要取出来Body部分,不能带参数 + prop + ); + Expression rightExpr = Convert(Constant(otherValue), propType); + if (propType.IsPrimitive)//基本数据类型和复杂类型比较方法不一样 + { + equalExpr = Equal(leftExpr, rightExpr); + } + else + { + equalExpr = MakeBinary(ExpressionType.Equal, + leftExpr, rightExpr, false, + prop.PropertyType.GetMethod("op_Equality") ); - Expression rightExpr = Convert(Constant(otherValue), propType); - if (propType.IsPrimitive)//基本数据类型和复杂类型比较方法不一样 - { - equalExpr = Equal(leftExpr, rightExpr); - } - else - { - equalExpr = MakeBinary(ExpressionType.Equal, - leftExpr, rightExpr, false, - prop.PropertyType.GetMethod("op_Equality") - ); - } - if (conditionalExpr == null) - { - conditionalExpr = equalExpr; - } - else - { - conditionalExpr = AndAlso(conditionalExpr, equalExpr); - } } if (conditionalExpr == null) { - throw new ArgumentException("There should be at least one property."); + conditionalExpr = equalExpr; + } + else + { + conditionalExpr = AndAlso(conditionalExpr, equalExpr); } - return Lambda>(conditionalExpr, e1); + } + if (conditionalExpr == null) + { + throw new ArgumentException("There should be at least one property."); + } + return Lambda>(conditionalExpr, e1); } } \ No newline at end of file diff --git "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Infrastructure/EFCore/MediatorExtensions.cs" "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Infrastructure/EFCore/MediatorExtensions.cs" index fd4a06e..a4a7430 100644 --- "a/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Infrastructure/EFCore/MediatorExtensions.cs" +++ "b/\346\234\200\345\220\216\345\244\247\351\241\271\347\233\256\344\273\243\347\240\201/YouZack-VNext/Zack.Infrastructure/EFCore/MediatorExtensions.cs" @@ -1,6 +1,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; +using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; @@ -11,20 +11,15 @@ namespace MediatR { public static class MediatorExtensions { - public static IServiceCollection AddMediatR(this IServiceCollection services, Type rootType) - { - return AddMediatR(services, rootType.Assembly); - } /// /// 把rootAssembly及直接或者间接引用的程序集(排除系统程序集)中的MediatR 相关类进行注册 /// /// /// /// - public static IServiceCollection AddMediatR(this IServiceCollection services, Assembly rootAssembly) + public static IServiceCollection AddMediatR(this IServiceCollection services,IEnumerable assemblies) { - var asms = ReflectionHelper.GetAllReferencedAssemblies(rootAssembly); - return services.AddMediatR(asms.ToArray()); + return services.AddMediatR(assemblies.ToArray()); } public static async Task DispatchDomainEventsAsync(this IMediator mediator, DbContext ctx) { diff --git "a/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226MSTest/UnitTest1.cs" "b/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226MSTest/UnitTest1.cs" new file mode 100644 index 0000000..de92664 --- /dev/null +++ "b/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226MSTest/UnitTest1.cs" @@ -0,0 +1,23 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Linq; +using System.Reflection; +using 例子服务接口1; +using 模块化服务注册框架; + +namespace 模块化MSTest +{ + [TestClass] + public class UnitTest1 + { + [TestMethod] + public void TestMethod1() + { + ServiceCollection services = new ServiceCollection(); + ModuleHelper.RunModuleInitializers(services); + using var sp = services.BuildServiceProvider(); + var items = sp.GetServices(); + Assert.AreEqual(items.Count(), 2); + } + } +} \ No newline at end of file diff --git "a/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226MSTest/\346\250\241\345\235\227\345\214\226MSTest.csproj" "b/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226MSTest/\346\250\241\345\235\227\345\214\226MSTest.csproj" new file mode 100644 index 0000000..b877432 --- /dev/null +++ "b/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226MSTest/\346\250\241\345\235\227\345\214\226MSTest.csproj" @@ -0,0 +1,26 @@ + + + + net6.0 + enable + + false + + + + + + + + + + + + + + + + + + + diff --git "a/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226\346\234\215\345\212\241\346\263\250\345\206\214\346\241\206\346\236\266/ModuleHelper.cs" "b/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226\346\234\215\345\212\241\346\263\250\345\206\214\346\241\206\346\236\266/ModuleHelper.cs" index aae7c3f..3f8a496 100644 --- "a/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226\346\234\215\345\212\241\346\263\250\345\206\214\346\241\206\346\236\266/ModuleHelper.cs" +++ "b/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226\346\234\215\345\212\241\346\263\250\345\206\214\346\241\206\346\236\266/ModuleHelper.cs" @@ -1,24 +1,14 @@ using Microsoft.Extensions.DependencyInjection; -using System.Reflection; +using Zack.Commons; using 模块化的服务注册; namespace 模块化服务注册框架; public static class ModuleHelper { - public static IServiceCollection RunModuleInitializers(this IServiceCollection services, Type rootType) - { - return RunModuleInitializers(services, rootType.Assembly); - } - - public static IServiceCollection RunModuleInitializers(this IServiceCollection services, Assembly rootAssembly) - { - var asms = ReflectionHelper.GetAllReferencedAssemblies(rootAssembly); - return RunModuleInitializers(services, asms); - } - - public static IServiceCollection RunModuleInitializers(this IServiceCollection services, IEnumerable assemblies) + public static IServiceCollection RunModuleInitializers(this IServiceCollection services) { + var assemblies = ReflectionHelper.GetAllReferencedAssemblies(); foreach (var implType in assemblies.SelectMany(asm => asm.GetTypes()) .Where(t => !t.IsAbstract && typeof(IModuleInitializer).IsAssignableFrom(t))) { diff --git "a/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226\346\234\215\345\212\241\346\263\250\345\206\214\346\241\206\346\236\266/ReflectionHelper.cs" "b/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226\346\234\215\345\212\241\346\263\250\345\206\214\346\241\206\346\236\266/ReflectionHelper.cs" index 5a21315..24a9732 100644 --- "a/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226\346\234\215\345\212\241\346\263\250\345\206\214\346\241\206\346\236\266/ReflectionHelper.cs" +++ "b/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226\346\234\215\345\212\241\346\263\250\345\206\214\346\241\206\346\236\266/ReflectionHelper.cs" @@ -1,104 +1,129 @@ using System.Diagnostics.CodeAnalysis; using System.Reflection; +using System.Reflection.PortableExecutable; -namespace 模块化服务注册框架 +namespace Zack.Commons; +public static class ReflectionHelper { - public static class ReflectionHelper + //是否是微软等的官方Assembly + private static bool IsSystemAssembly(Assembly asm) { - //是否是微软等的官方Assembly - private static bool IsSystemAssembly(Assembly asm) + var asmCompanyAttr = asm.GetCustomAttribute(); + if (asmCompanyAttr == null) { - var asmCompanyAttr = asm.GetCustomAttribute(); - if (asmCompanyAttr == null) - { - return false; - } - else - { - string companyName = asmCompanyAttr.Company; - return companyName.Contains("Microsoft Corporation"); - } + return false; + } + else + { + string companyName = asmCompanyAttr.Company; + return companyName.Contains("Microsoft"); } + } + + private static bool IsManagedAssembly(string file) + { + using var fs = File.OpenRead(file); + using PEReader peReader = new PEReader(fs); + var peHeaders = peReader.PEHeaders; + return peHeaders.CorHeader != null; + /* + using var fs1 = File.OpenRead(@"E:\主同步盘\我的坚果云\个人资料\写书\Net Core书稿\随书代码\最后大项目代码\YouZack-VNext\Listening.Admin.WebAPI\bin\Debug\net6.0\runtimes\win-arm\native\Microsoft.Data.SqlClient.SNI.dll"); + using PEReader peReader1 = new PEReader(fs1); + var peHeaders1 = peReader1.PEHeaders; + using var fs2 = File.OpenRead(@"E:\主同步盘\我的坚果云\个人资料\写书\Net Core书稿\随书代码\最后大项目代码\YouZack-VNext\Listening.Admin.WebAPI\bin\Debug\net6.0\System.Data.SqlClient.dll"); + using PEReader peReader2 = new PEReader(fs2); + var peHeaders2 = peReader2.PEHeaders; + string s1 = peHeaders1.ToJsonString(); + string s2 = peHeaders2.ToJsonString();*/ + //return true; + } - /// - /// loop through all assemblies + /// + /// loop through all assemblies + /// + /// + public static IEnumerable GetAllReferencedAssemblies(bool skipSystemAssemblies = true) + { /// 对于MSTest项目启动,Assembly.GetEntryAssembly()是"TestHost",而"TestHost"的GetReferencedAssemblies /// 不包含项目的Dll,可能是因为"TestHost"都是通过Http调用被测试的程序集导致的,因此必须传入一个跟rootAssembly /// https://dotnetcoretutorials.com/2020/07/03/getting-assemblies-is-harder-than-you-think-in-c/ - /// - /// - public static IEnumerable GetAllReferencedAssemblies(Assembly rootAssembly, bool skipSystemAssemblies = true) + Assembly? rootAssembly = Assembly.GetEntryAssembly(); + if (rootAssembly == null) + { + rootAssembly = Assembly.GetCallingAssembly(); + } + var returnAssemblies = new HashSet(new AssemblyEquality()); + var loadedAssemblies = new HashSet(); + var assembliesToCheck = new Queue(); + assembliesToCheck.Enqueue(rootAssembly); + if (skipSystemAssemblies && IsSystemAssembly(rootAssembly) != false) { - if (skipSystemAssemblies && IsSystemAssembly(rootAssembly)) - { - throw new ArgumentOutOfRangeException(nameof(rootAssembly), "rootAssembly cannot be system-level assembly"); - } - var returnAssemblies = new HashSet(new AssemblyEquality()); - var loadedAssemblies = new HashSet(); - var assembliesToCheck = new Queue(); - - assembliesToCheck.Enqueue(rootAssembly); returnAssemblies.Add(rootAssembly); - - while (assembliesToCheck.Any()) + } + while (assembliesToCheck.Any()) + { + var assemblyToCheck = assembliesToCheck.Dequeue(); + foreach (var reference in assemblyToCheck.GetReferencedAssemblies()) { - var assemblyToCheck = assembliesToCheck.Dequeue(); - - foreach (var reference in assemblyToCheck.GetReferencedAssemblies()) + if (!loadedAssemblies.Contains(reference.FullName)) { - if (!loadedAssemblies.Contains(reference.FullName)) + var assembly = Assembly.Load(reference); + if (skipSystemAssemblies && IsSystemAssembly(assembly)) { - var assembly = Assembly.Load(reference); - if (skipSystemAssemblies && IsSystemAssembly(assembly)) - { - continue; - } - assembliesToCheck.Enqueue(assembly); - loadedAssemblies.Add(reference.FullName); - returnAssemblies.Add(assembly); + continue; } + assembliesToCheck.Enqueue(assembly); + loadedAssemblies.Add(reference.FullName); + returnAssemblies.Add(assembly); } } - //如果一个程序集被引用了,但是我们没有直接用在代码中静态使用其中的类, - //而是使用反射的形式使用了那些类, - //那么我们是无法用GetReferencedAssemblies获得这个程序集的 - //因此这里通过扫描运行目录下的dll的形式再去补偿获取一些之前可能没扫描的程序集, - //当然,在项目【发布】的时候,可能已经没有静态引用的程序集就没有被生成, - //因此,如果遇到这种情况,就需要我们在代码中显式的静态引用那个程序集中的一个类了。 - var asmsInBaseDir = Directory.EnumerateFiles(AppContext.BaseDirectory, - "*.dll", new EnumerationOptions { RecurseSubdirectories = true }); - foreach (var asmPath in asmsInBaseDir) - { - Assembly asm; - try - { - asm = Assembly.LoadFile(asmPath); - } - catch (BadImageFormatException) - { - continue; - } - if (skipSystemAssemblies && IsSystemAssembly(asm)) - { - continue; - } - returnAssemblies.Add(asm); - } - return returnAssemblies.ToArray(); } - class AssemblyEquality : EqualityComparer + //以下代码解决两个问题: + //1、如果一个程序集被引用了,但是我们没有直接用在代码中静态使用其中的类, + //而是使用反射的形式使用了那些类, + //那么我们是无法用GetReferencedAssemblies获得这个程序集的 + //2、以MsTest运行的时候GetEntryAssembly()拿到的是TestHost,从而无法进一步的获取它引用的程序集。 + //"TestHost"的GetReferencedAssemblies不包含项目的Dll,可能是因为"TestHost" + //都是通过Http调用被测试的程序集导致的。 + //https://dotnetcoretutorials.com/2020/07/03/getting-assemblies-is-harder-than-you-think-in-c/ + //因此这里通过扫描运行目录下的dll的形式再去补偿获取一些之前可能没扫描的程序集, + //当然,在项目【发布】的时候,可能已经没有静态引用的程序集就没有被生成, + //因此,如果遇到这种情况,就需要我们在代码中显式的静态引用那个程序集中的一个类了。 + var asmsInBaseDir = Directory.EnumerateFiles(AppContext.BaseDirectory, + "*.dll", new EnumerationOptions { RecurseSubdirectories = true }); + foreach (var asmPath in asmsInBaseDir) { - public override bool Equals(Assembly? x, Assembly? y) + if (!IsManagedAssembly(asmPath)) { - if (x == null && y == null) return true; - if (x == null || y == null) return false; - return AssemblyName.ReferenceMatchesDefinition(x.GetName(), y.GetName()); + continue; } - - public override int GetHashCode([DisallowNull] Assembly obj) + AssemblyName asmName = AssemblyName.GetAssemblyName(asmPath); + //如果程序集已经加载过了就不再加载 + if (returnAssemblies.Any(x => AssemblyName.ReferenceMatchesDefinition(x.GetName(), asmName))) { - return obj.GetName().FullName.GetHashCode(); + continue; } + Assembly asm = Assembly.Load(asmName); + if (skipSystemAssemblies && IsSystemAssembly(asm)) + { + continue; + } + returnAssemblies.Add(asm); + } + return returnAssemblies.ToArray(); + } + class AssemblyEquality : EqualityComparer + { + public override bool Equals(Assembly? x, Assembly? y) + { + if (x == null && y == null) return true; + if (x == null || y == null) return false; + return AssemblyName.ReferenceMatchesDefinition(x.GetName(), y.GetName()); + } + + public override int GetHashCode([DisallowNull] Assembly obj) + { + return obj.GetName().FullName.GetHashCode(); } } } \ No newline at end of file diff --git "a/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226\346\265\213\350\257\225\347\250\213\345\272\2171/Program.cs" "b/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226\346\265\213\350\257\225\347\250\213\345\272\2171/Program.cs" index e698c36..d3c3f2f 100644 --- "a/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226\346\265\213\350\257\225\347\250\213\345\272\2171/Program.cs" +++ "b/\347\254\254\344\270\203\347\253\240/\346\250\241\345\235\227\345\214\226\346\265\213\350\257\225\347\250\213\345\272\2171/Program.cs" @@ -4,8 +4,7 @@ using 模块化服务注册框架; ServiceCollection services = new ServiceCollection(); -var asm = Assembly.GetExecutingAssembly(); -ModuleHelper.RunModuleInitializers(services, asm); +ModuleHelper.RunModuleInitializers(services); using var sp = services.BuildServiceProvider(); var items = sp.GetServices(); foreach(var item in items) diff --git "a/\347\254\254\344\270\203\347\253\240/\347\254\254\344\270\203\347\253\240.sln" "b/\347\254\254\344\270\203\347\253\240/\347\254\254\344\270\203\347\253\240.sln" index ffa8e82..71c6034 100644 --- "a/\347\254\254\344\270\203\347\253\240/\347\254\254\344\270\203\347\253\240.sln" +++ "b/\347\254\254\344\270\203\347\253\240/\347\254\254\344\270\203\347\253\240.sln" @@ -17,6 +17,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "例子服务实现2", "例 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "模块化测试程序1", "模块化测试程序1\模块化测试程序1.csproj", "{6F80361E-CBEC-4DBC-8460-D4D6D5EBEF58}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "模块化MSTest", "模块化MSTest\模块化MSTest.csproj", "{09F49509-5764-40CF-910E-A1AC7EDBD24D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -47,6 +49,10 @@ Global {6F80361E-CBEC-4DBC-8460-D4D6D5EBEF58}.Debug|Any CPU.Build.0 = Debug|Any CPU {6F80361E-CBEC-4DBC-8460-D4D6D5EBEF58}.Release|Any CPU.ActiveCfg = Release|Any CPU {6F80361E-CBEC-4DBC-8460-D4D6D5EBEF58}.Release|Any CPU.Build.0 = Release|Any CPU + {09F49509-5764-40CF-910E-A1AC7EDBD24D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {09F49509-5764-40CF-910E-A1AC7EDBD24D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {09F49509-5764-40CF-910E-A1AC7EDBD24D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {09F49509-5764-40CF-910E-A1AC7EDBD24D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -57,6 +63,7 @@ Global {131A7661-2F59-4E10-B2BB-592E1287BB0A} = {7C7B90A4-0663-450C-8547-01D4E2764563} {EECF27FC-B89F-41F6-AEA9-720C45F85607} = {7C7B90A4-0663-450C-8547-01D4E2764563} {6F80361E-CBEC-4DBC-8460-D4D6D5EBEF58} = {7C7B90A4-0663-450C-8547-01D4E2764563} + {09F49509-5764-40CF-910E-A1AC7EDBD24D} = {7C7B90A4-0663-450C-8547-01D4E2764563} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {A91AAEA9-15AC-41AD-A1E4-A445447BE325}