DependencyInjection.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. using Application.Abstractions.Authentication;
  2. using Application.Abstractions.Cache;
  3. using Application.Abstractions.Chat;
  4. using Application.Abstractions.Crypto;
  5. using Application.Abstractions.Data;
  6. using Application.Abstractions.Hub;
  7. using Application.Abstractions.Identity;
  8. using Application.Abstractions.Forum;
  9. using Application.Abstractions.Messaging.Email;
  10. using Application.Abstractions.Notification;
  11. using Application.Abstractions.Payment;
  12. using Application.Abstractions.YouTube;
  13. using Infrastructure.Authentication;
  14. using Infrastructure.Crypto;
  15. using Infrastructure.Payment;
  16. using Infrastructure.Forum;
  17. using Infrastructure.Cache;
  18. using Infrastructure.Chat;
  19. using Infrastructure.Messaging.Email;
  20. using Infrastructure.Persistence;
  21. using Infrastructure.Persistence.Identity;
  22. using Infrastructure.Storage;
  23. using Infrastructure.YouTube;
  24. using Microsoft.AspNetCore.Authentication;
  25. using Microsoft.AspNetCore.Authentication.JwtBearer;
  26. using Microsoft.AspNetCore.DataProtection;
  27. using Microsoft.AspNetCore.Identity;
  28. using Microsoft.AspNetCore.Identity.UI.Services;
  29. using Microsoft.EntityFrameworkCore;
  30. using Microsoft.EntityFrameworkCore.Diagnostics;
  31. using Microsoft.Extensions.Configuration;
  32. using Microsoft.Extensions.DependencyInjection;
  33. using Microsoft.Extensions.Options;
  34. using Microsoft.IdentityModel.Tokens;
  35. using SharedKernel;
  36. using SharedKernel.Storage;
  37. using StackExchange.Redis;
  38. using System.Text;
  39. namespace Infrastructure;
  40. public static class DependencyInjection
  41. {
  42. // SQL Server
  43. private static IServiceCollection AddDatabase(this IServiceCollection services, IConfiguration configuration)
  44. {
  45. var dbConn = configuration.GetConnectionString("DefaultConnection");
  46. if (string.IsNullOrWhiteSpace(dbConn))
  47. {
  48. throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured.");
  49. }
  50. // Pooling: 매 request 마다 새 DbContext 생성 비용 제거. ChangeTracker 등 내부 상태는 풀 반환 시 자동 reset
  51. // ConfigureWarnings: EF 9+의 PendingModelChangesWarning을 무시 (snapshot 일관성 문제로 false-positive 발생, 마이그레이션은 별도 관리)
  52. services.AddDbContextPool<AppDbContext>(options => options
  53. .UseSqlServer(dbConn)
  54. .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning)), poolSize: 128);
  55. services.AddDbContextPool<IdentityDbContext>(options => options
  56. .UseSqlServer(dbConn)
  57. .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning)), poolSize: 64);
  58. services.AddScoped<IAppDbContext>(sp => sp.GetRequiredService<AppDbContext>());
  59. return services;
  60. }
  61. // Redis Server
  62. public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
  63. {
  64. var settings = configuration.Get<AppSettings>()!;
  65. var redis = ConnectionMultiplexer.Connect(settings.Redis.DefaultConnection);
  66. services.AddSingleton<IConnectionMultiplexer>(redis);
  67. services.AddDataProtection()
  68. .SetApplicationName(settings.App.Name)
  69. .PersistKeysToStackExchangeRedis(redis, settings.Redis.DataProtectionKey)
  70. .ProtectKeysWithDpapi(protectToLocalMachine: true) // key를 암호화하여 저장 (로컬 머신에서만 복호화 가능, 서버간 공유 불가)
  71. .SetDefaultKeyLifetime(settings.Redis.DefaultKeyLifetime); // 기본 90일 주기
  72. // Distributed Cache 설정
  73. services.AddStackExchangeRedisCache(options =>
  74. {
  75. options.Configuration = settings.Redis.DefaultConnection;
  76. options.InstanceName = settings.Redis.CachePrefix;
  77. });
  78. return services;
  79. }
  80. private static IServiceCollection AddHealthChecks(this IServiceCollection services, IConfiguration configuration)
  81. {
  82. var settings = configuration.Get<AppSettings>()!;
  83. services.AddHealthChecks().AddSqlServer(settings.ConnectionStrings.DefaultConnection).AddRedis(settings.Redis.DefaultConnection);
  84. return services;
  85. }
  86. // Admin/Api 둘 다 필요한 공용 서비스 (singleton/transient/scoped, HttpClient)
  87. private static IServiceCollection AddCommonServices(this IServiceCollection services, IConfiguration configuration)
  88. {
  89. // 파일 저장 위치 옵션 (deploy 영향 받지 않는 외부 경로 권장)
  90. services.Configure<StorageOptions>(configuration.GetSection(StorageOptions.SectionName));
  91. services.AddSingleton<IJwtTokenProvider, JwtTokenProvider>();
  92. services.AddSingleton<ILegacyPasswordVerifier, BcryptLegacyPasswordVerifier>();
  93. services.AddSingleton<ICacheService, RedisCacheService>();
  94. services.AddSingleton<IFieldEncryptor, AesGcmFieldEncryptor>();
  95. services.AddTransient<IEmailSender, IdentityEmailSender>();
  96. services.AddScoped<IFileStorage, LocalFileStorage>();
  97. services.AddScoped<IEditorImageService, EditorImageService>();
  98. services.AddScoped<IIdentityUserReader, IdentityUserReader>();
  99. services.AddScoped<IIdentityUserWriter, IdentityUserWriter>();
  100. services.AddScoped<IIdentityRoleReader, IdentityRoleReader>();
  101. services.AddScoped<IIdentityRoleWriter, IdentityRoleWriter>();
  102. services.AddSingleton<IChatMessageStore, RedisChatMessageStore>();
  103. services.AddSingleton<IChatConnectionTracker, RedisChatConnectionTracker>();
  104. services.AddSingleton<IChatLeaderboard, RedisChatLeaderboard>();
  105. services.AddSingleton<IPresenceTracker, Hubs.PresenceTracker>();
  106. services.AddSingleton<IVisitorTracker, Hubs.RedisVisitorTracker>();
  107. services.AddScoped<IBoardPermissionService, BoardPermissionService>();
  108. services.AddHttpClient<IGoogleTokenValidator, GoogleTokenValidator>();
  109. // YouTube & Google OAuth (HttpClients + singletons — Admin에서도 "API 키 테스트" 등에 쓰므로 공용)
  110. services.AddSingleton<IYouTubeApiKeyProvider, YouTubeApiKeyProvider>();
  111. services.AddTransient<YouTubeApiKeyHandler>();
  112. services.AddTransient<IYouTubeApiConnectionTester, YouTubeApiConnectionTester>();
  113. services.AddHttpClient("YouTubeApi", client =>
  114. {
  115. client.Timeout = TimeSpan.FromSeconds(15);
  116. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  117. })
  118. .AddHttpMessageHandler<YouTubeApiKeyHandler>();
  119. services.AddHttpClient("PubSubHub", client =>
  120. {
  121. client.Timeout = TimeSpan.FromSeconds(15);
  122. });
  123. services.AddHttpClient("YouTubeFeed", client =>
  124. {
  125. client.Timeout = TimeSpan.FromSeconds(10);
  126. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/atom+xml"));
  127. });
  128. services.AddHttpClient<IGoogleOAuthService, GoogleOAuthService>();
  129. services.AddHttpClient<IDanalPayService, DanalPayService>();
  130. services.AddSingleton<IYouTubeApiService, YouTubeApiService>();
  131. services.AddSingleton<IYouTubeChannelCache, YouTubeChannelCache>();
  132. services.AddSingleton<IYouTubeLiveStateStore, YouTubeLiveStateStore>();
  133. services.AddSingleton<YouTubeLiveChatService>();
  134. services.AddSingleton<IYouTubeLiveChatService>(sp => sp.GetRequiredService<YouTubeLiveChatService>());
  135. services.AddSingleton<YouTubePubSubService>();
  136. services.AddSingleton<IYouTubePubSubService>(sp => sp.GetRequiredService<YouTubePubSubService>());
  137. services.AddSingleton<IYouTubeFeedPoller, YouTubeFeedPoller>();
  138. // Notification
  139. services.AddScoped<INotificationService, Notification.NotificationService>();
  140. // Feed broadcaster (SignalR)
  141. services.AddScoped<IFeedBroadcaster, Hubs.FeedBroadcaster>();
  142. // Channel status broadcaster (라이브 시작/종료/시청자 수 → AppHub 브로드캐스트)
  143. services.AddSingleton<IChannelStatusBroadcaster, Hubs.ChannelStatusBroadcaster>();
  144. return services;
  145. }
  146. // Web.Api 전용 백그라운드 서비스 (Admin에서 중복 실행되면 quota 2배/폴링 2번 문제)
  147. // appsettings.json BackgroundJobs 섹션으로 개별 토글 (기본 모두 true). 진단용 A/B 테스트에 사용
  148. private static IServiceCollection AddBackgroundServices(this IServiceCollection services, IConfiguration configuration)
  149. {
  150. // Features:Channel OFF → YouTube/채널 백그라운드 서비스 전체 미등록 (코드 보존, 기능 노출 0)
  151. var features = configuration.GetSection("Features").Get<AppSettings.FeaturesSection>() ?? new AppSettings.FeaturesSection();
  152. if (!features.Channel)
  153. {
  154. return services;
  155. }
  156. var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
  157. if (bg.LiveChat)
  158. {
  159. services.AddHostedService(sp => sp.GetRequiredService<YouTubeLiveChatService>());
  160. }
  161. if (bg.PubSubRenewal)
  162. {
  163. services.AddHostedService<YouTubePubSubRenewalService>();
  164. }
  165. if (bg.FeedPolling)
  166. {
  167. services.AddHostedService<YouTubeFeedPollingService>();
  168. }
  169. if (bg.LiveViewerPoller)
  170. {
  171. services.AddHostedService<YouTubeLiveViewerPoller>();
  172. }
  173. if (bg.ChannelCacheRefresh)
  174. {
  175. services.AddHostedService<YouTubeChannelCacheRefreshService>();
  176. }
  177. if (bg.YouTubeDailyAggregator)
  178. {
  179. services.AddHostedService<YouTubeDailyAggregatorService>();
  180. }
  181. if (bg.YouTubeStaleDataPurge)
  182. {
  183. services.AddHostedService<YouTubeStaleDataPurgeService>();
  184. }
  185. return services;
  186. }
  187. /**
  188. * ========================================================================================================================================================================================================
  189. * ========================================================================================================================================================================================================
  190. */
  191. // Admin 전용 — 백그라운드 서비스는 포함하지 않음 (Web.Api에서만 돌아야 함)
  192. // 메일은 즉시 SMTP 발송 (DirectMailService)
  193. public static IServiceCollection AddAdminInfrastructure(this IServiceCollection services, IConfiguration configuration)
  194. {
  195. services.AddScoped<IMailService, DirectMailService>();
  196. return services.AddDatabase(configuration).AddRedis(configuration).AddCommonServices(configuration).AddHealthChecks(configuration);
  197. }
  198. /**
  199. * ========================================================================================================================================================================================================
  200. * ========================================================================================================================================================================================================
  201. */
  202. // API 전용 — 공용 서비스 + 백그라운드 서비스 모두 포함
  203. // 메일은 EmailLog 큐에 적재 (QueuedMailService) — MailWorker가 별도로 폴링하여 SMTP 송신
  204. public static IServiceCollection AddApiInfrastructure(this IServiceCollection services, IConfiguration configuration)
  205. {
  206. services.AddScoped<IMailService, QueuedMailService>();
  207. return services.AddDatabase(configuration).AddRedis(configuration).AddApiAuthentication(configuration).AddCommonServices(configuration).AddBackgroundServices(configuration).AddHealthChecks(configuration);
  208. }
  209. private static IServiceCollection AddApiAuthentication(this IServiceCollection services, IConfiguration configuration)
  210. {
  211. var settings = configuration.Get<AppSettings>()!;
  212. // 인증 정책- JWT Bearer
  213. services.AddAuthentication(options =>
  214. {
  215. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  216. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  217. })
  218. .AddJwtBearer(options =>
  219. {
  220. options.RequireHttpsMetadata = false;
  221. options.MapInboundClaims = false;
  222. options.TokenValidationParameters = new TokenValidationParameters
  223. {
  224. ValidateIssuer = true,
  225. ValidateAudience = true,
  226. ValidateLifetime = true,
  227. ValidateIssuerSigningKey = true,
  228. ValidIssuer = settings.JWT.Issuer,
  229. ValidAudience = settings.JWT.Audience,
  230. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.JWT.SecretKey)),
  231. ClockSkew = TimeSpan.Zero
  232. };
  233. options.Events = new JwtBearerEvents
  234. {
  235. OnMessageReceived = context =>
  236. {
  237. var accessToken = context.Request.Query["access_token"];
  238. var path = context.HttpContext.Request.Path;
  239. if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
  240. {
  241. context.Token = accessToken;
  242. }
  243. return Task.CompletedTask;
  244. }
  245. };
  246. });
  247. services.AddAuthorization();
  248. // Identity Core (Admin Handler의 UserManager/RoleManager 의존 해소용)
  249. services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
  250. return services;
  251. }
  252. }