Skip to content

Commit

Permalink
重构加载所有程序集的代码,不再需要StartupType
Browse files Browse the repository at this point in the history
  • Loading branch information
yangzhongke committed Nov 12, 2021
1 parent 6c45257 commit 0a5cec9
Show file tree
Hide file tree
Showing 50 changed files with 431 additions and 428 deletions.
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace CommonInitializer
{
public static class DbContextOptionsBuilderFactory
{
public static DbContextOptionsBuilder<TDbContext> Create<TDbContext>()
where TDbContext:DbContext
{
where TDbContext : DbContext
{
var connStr = Environment.GetEnvironmentVariable("DefaultDB:ConnStr");
var optionsBuilder = new DbContextOptionsBuilder<TDbContext>();
//optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=YouzackVNextDB;User ID=sa;Password=dLLikhQWy5TBz1uM;");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,7 @@ public class InitializerOptions
{
public string LogFilePath { get; set; }

/// <summary>
/// 入口项目的一个主要的类,会从这个类所在的程序集为根扫描所有程序进行IModuleInitializer等的遍历
/// </summary>
public Type StartupType { get; set; }

private string? applicationName;

/// <summary>
/// 应用程序名,默认值是StartupType所在的程序集的名字,可以手动修改。
/// 这个名字一般用于EventBus等用于标识这个应用,因此要维持“同一个项目值保持一直,不同项目不能冲突”
/// </summary>
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; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,18 @@ 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中,会有泄密的风险
//如果放到UserSecrets中,每个项目都要配置,很麻烦
//因此这里推荐放到环境变量中。
string connStr = configuration.GetValue<string>("DefaultDB:ConnStr");
ctx.UseSqlServer(connStr);
}, startupType);
}, assemblies);

//开始:Authentication,Authorization
//只要需要校验Authentication报文头的地方(非IdentityService.WebAPI项目)也需要启用这些
Expand All @@ -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<MvcOptions>(options=> {})这个问题很多都类似
services.Configure<MvcOptions>(options =>
{
Expand Down Expand Up @@ -94,22 +93,20 @@ 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<JWTOptions>(configuration.GetSection("JWT"));
services.Configure<IntegrationEventRabbitMQOptions>(configuration.GetSection("RabbitMQ"));
services.AddEventBus(initOptions.ApplicationName, startupType);
services.AddEventBus(initOptions.EventBusQueueName, assemblies);

//Redis的配置
string redisConnStr = configuration.GetValue<string>("Redis:ConnStr");
IConnectionMultiplexer redisConnMultiplexer = ConnectionMultiplexer.Connect(redisConnStr);
services.AddSingleton(typeof(IConnectionMultiplexer), redisConnMultiplexer);
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.All;
options.ForwardedHeaders = ForwardedHeaders.All;
});
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public FSRepository(FSDbContext dbContext)

public Task<UploadedItem?> FindFileAsync(long fileSize, string sha256Hash)
{
return dbContext.UploadItems.FirstOrDefaultAsync(u => u.FileSizeInBytes == fileSize
return dbContext.UploadItems.FirstOrDefaultAsync(u => u.FileSizeInBytes == fileSize
&& u.FileSHA256Hash == sha256Hash);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -10,7 +9,7 @@
builder.ConfigureExtraServices(new InitializerOptions
{
LogFilePath = "e:/temp/FileService.log",
StartupType = typeof(UploaderController)
EventBusQueueName = "FileService.WebAPI",
});

// Add services to the container.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public UploaderController(FSDomainService domainService, FSDbContext dbContext,
[HttpGet]
public async Task<FileExistsResponse> 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);
Expand Down
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public interface IIdRepository
/// <param name="id"></param>
/// <returns></returns>
public Task<IdentityResult> RemoveUserAsync(Guid id);

/// <summary>
/// 添加管理员
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public class IdDomainService
private readonly ITokenService tokenService;
private readonly IOptions<JWTOptions> optJWT;

public IdDomainService(IIdRepository repository,
ITokenService tokenService,IOptions<JWTOptions> optJWT)
public IdDomainService(IIdRepository repository,
ITokenService tokenService, IOptions<JWTOptions> optJWT)
{
this.repository = repository;
this.tokenService = tokenService;
Expand Down Expand Up @@ -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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

namespace IdentityService.Infrastructure
{
class IdRepository: IIdRepository
class IdRepository : IIdRepository
{
private readonly IdUserManager userManager;
private readonly RoleManager<Role> roleManager;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -65,7 +65,7 @@ public async Task<ActionResult<UserResponse>> GetUserInfo()
{
//todo:要通过行为验证码、图形验证码等形式来防止暴力破解
(var checkResult, string? token) = await idService.LoginByPhoneAndPwdAsync(req.PhoneNum, req.Password);
if(checkResult.Succeeded)
if (checkResult.Succeeded)
{
return token;
}
Expand All @@ -85,7 +85,7 @@ public async Task<ActionResult<UserResponse>> GetUserInfo()
[HttpPost]
public async Task<ActionResult<string>> 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!;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public async Task<UserDTO> FindById(Guid id)
[HttpPost]
public async Task<ActionResult> 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)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Identity.Repository;
using Microsoft.Extensions.Logging;
using Zack.EventBus;

namespace IdentityService.WebAPI.Events
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
global using System;
global using System.Collections.Generic;
global using System.Threading.Tasks;
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:61250",
"sslPort": 44392
"applicationUrl": "http://localhost:6802/",
"sslPort": 44395
}
},
"profiles": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public Task<Album[]> FindByCategoryId([RequiredGuid] Guid categoryId)
[HttpPost]
public async Task<ActionResult<Guid>> 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;
}
Expand All @@ -46,7 +46,7 @@ public async Task<ActionResult<Guid>> Add(AlbumAddRequest req)
public async Task<ActionResult> Update([RequiredGuid] Guid id, AlbumUpdateRequest request)
{
var album = await repository.GetAlbumByIdAsync(id);
if(album==null)
if (album == null)
{
return NotFound("id没找到");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public async Task<ActionResult<Guid>> Add(CategoryAddRequest req)
public async Task<ActionResult> Update([RequiredGuid] Guid id, CategoryUpdateRequest request)
{
var cat = await repository.GetCategoryByIdAsync(id);
if(cat==null)
if (cat == null)
{
return NotFound("id不存在");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ public async Task<ActionResult<Guid>> 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;
}
Expand All @@ -54,7 +54,7 @@ public async Task<ActionResult<Guid>> Add(EpisodeAddRequest req)
public async Task<ActionResult> Update([RequiredGuid] Guid id, EpisodeUpdateRequest request)
{
var episode = await repository.GetEpisodeByIdAsync(id);
if(episode==null)
if (episode == null)
{
return NotFound("id没找到");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class MediaEncodingStatusChangeIntegrationHandler : DynamicIntegrationEventHandl
private readonly EncodingEpisodeHelper encHelper;
private readonly IHubContext<EpisodeEncodingStatusHub> hubContext;

public MediaEncodingStatusChangeIntegrationHandler(ListeningDbContext dbContext,
public MediaEncodingStatusChangeIntegrationHandler(ListeningDbContext dbContext,
EncodingEpisodeHelper encHelper,
IHubContext<EpisodeEncodingStatusHub> hubContext, IListeningRepository repository)
{
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using CommonInitializer;
using Listening.Admin.WebAPI.Albums;
using Listening.Admin.WebAPI.Hubs;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -10,7 +9,7 @@
builder.ConfigureExtraServices(new InitializerOptions
{
LogFilePath = "e:/temp/Listening.Admin.log",
StartupType = typeof(AlbumController)
EventBusQueueName = "Listening.Admin"
});
builder.Services.AddScoped<EncodingEpisodeHelper>();
builder.Services.AddControllers();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand All @@ -178,7 +178,7 @@ public Episode Build()
{
throw new ArgumentNullException(nameof(audioUrl));
}
if(durationInSecond<=0)
if (durationInSecond <= 0)
{
throw new ArgumentOutOfRangeException(nameof(durationInSecond));
}
Expand Down
Loading

0 comments on commit 0a5cec9

Please sign in to comment.