DependencyInjection.cs 15 KB

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