DependencyInjection.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. void ConfigureAppDb(DbContextOptionsBuilder options) => options
  54. .UseSqlServer(dbConn)
  55. .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning));
  56. services.AddDbContextPool<AppDbContext>(ConfigureAppDb, poolSize: 128);
  57. services.AddDbContextPool<IdentityDbContext>(options => options
  58. .UseSqlServer(dbConn)
  59. .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning)), poolSize: 64);
  60. services.AddScoped<IAppDbContext>(sp => sp.GetRequiredService<AppDbContext>());
  61. // Phase 1.5: out-of-band 커밋(대사 로그·동시성 재시도)용 풀링 팩토리.
  62. // 내부 등록이 전부 TryAdd 라 위 AddDbContextPool 과 같은 옵션·풀을 공유하며 중복 등록 없이 공존한다.
  63. services.AddPooledDbContextFactory<AppDbContext>(ConfigureAppDb, poolSize: 128);
  64. services.AddSingleton<IAppDbContextFactory, AppDbContextFactory>();
  65. return services;
  66. }
  67. // Redis Server
  68. public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
  69. {
  70. var settings = configuration.Get<AppSettings>()!;
  71. var redis = ConnectionMultiplexer.Connect(settings.Redis.DefaultConnection);
  72. services.AddSingleton<IConnectionMultiplexer>(redis);
  73. services.AddDataProtection()
  74. .SetApplicationName(settings.App.Name)
  75. .PersistKeysToStackExchangeRedis(redis, settings.Redis.DataProtectionKey)
  76. .ProtectKeysWithDpapi(protectToLocalMachine: true) // key를 암호화하여 저장 (로컬 머신에서만 복호화 가능, 서버간 공유 불가)
  77. .SetDefaultKeyLifetime(settings.Redis.DefaultKeyLifetime); // 기본 90일 주기
  78. // Distributed Cache 설정
  79. services.AddStackExchangeRedisCache(options =>
  80. {
  81. options.Configuration = settings.Redis.DefaultConnection;
  82. options.InstanceName = settings.Redis.CachePrefix;
  83. });
  84. return services;
  85. }
  86. private static IServiceCollection AddHealthChecks(this IServiceCollection services, IConfiguration configuration)
  87. {
  88. var settings = configuration.Get<AppSettings>()!;
  89. services.AddHealthChecks().AddSqlServer(settings.ConnectionStrings.DefaultConnection).AddRedis(settings.Redis.DefaultConnection);
  90. return services;
  91. }
  92. // Admin/Api 둘 다 필요한 공용 서비스 (singleton/transient/scoped, HttpClient)
  93. private static IServiceCollection AddCommonServices(this IServiceCollection services, IConfiguration configuration)
  94. {
  95. // 파일 저장 위치 옵션 (deploy 영향 받지 않는 외부 경로 권장)
  96. services.Configure<StorageOptions>(configuration.GetSection(StorageOptions.SectionName));
  97. services.AddSingleton<IJwtTokenProvider, JwtTokenProvider>();
  98. services.AddSingleton<ILegacyPasswordVerifier, BcryptLegacyPasswordVerifier>();
  99. services.AddSingleton<ICacheService, RedisCacheService>();
  100. services.AddSingleton<IFieldEncryptor, AesGcmFieldEncryptor>();
  101. services.AddTransient<IEmailSender, IdentityEmailSender>();
  102. services.AddScoped<IFileStorage, LocalFileStorage>();
  103. services.AddScoped<IEditorImageService, EditorImageService>();
  104. services.AddScoped<IIdentityUserReader, IdentityUserReader>();
  105. services.AddScoped<IIdentityUserWriter, IdentityUserWriter>();
  106. services.AddScoped<IIdentityRoleReader, IdentityRoleReader>();
  107. services.AddScoped<IIdentityRoleWriter, IdentityRoleWriter>();
  108. services.AddSingleton<IChatMessageStore, RedisChatMessageStore>();
  109. services.AddSingleton<IChatConnectionTracker, RedisChatConnectionTracker>();
  110. services.AddSingleton<IChatLeaderboard, RedisChatLeaderboard>();
  111. services.AddSingleton<Application.Abstractions.Paper.IPaperLeaderboardCache, Paper.PaperLeaderboardCache>();
  112. services.AddSingleton<Application.Abstractions.Stocks.IStockBoardTrendingCache, Stocks.RedisStockBoardTrendingCache>();
  113. services.AddSingleton<IChatRewardHook, RewardChatHook>(); // D3 M2 실구현 — ChatExpConfig 수치를 RewardService 로 지급 (d0 §2.2)
  114. services.AddSingleton<IPresenceTracker, Hubs.PresenceTracker>();
  115. services.AddSingleton<IVisitorTracker, Hubs.RedisVisitorTracker>();
  116. services.AddScoped<IBoardPermissionService, BoardPermissionService>();
  117. services.AddHttpClient<IGoogleTokenValidator, GoogleTokenValidator>();
  118. // 소셜 로그인 provider (개미투자 D5 — Naver/Kakao authorization code). 핸들러가 IEnumerable 에서 이름으로 해석
  119. services.AddHttpClient<NaverAuthProvider>();
  120. services.AddHttpClient<KakaoAuthProvider>();
  121. services.AddTransient<ISocialAuthProvider>(sp => sp.GetRequiredService<NaverAuthProvider>());
  122. services.AddTransient<ISocialAuthProvider>(sp => sp.GetRequiredService<KakaoAuthProvider>());
  123. // YouTube & Google OAuth (HttpClients + singletons — Admin에서도 "API 키 테스트" 등에 쓰므로 공용)
  124. services.AddSingleton<IYouTubeApiKeyProvider, YouTubeApiKeyProvider>();
  125. services.AddTransient<YouTubeApiKeyHandler>();
  126. services.AddTransient<IYouTubeApiConnectionTester, YouTubeApiConnectionTester>();
  127. services.AddHttpClient("YouTubeApi", client =>
  128. {
  129. client.Timeout = TimeSpan.FromSeconds(15);
  130. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  131. })
  132. .AddHttpMessageHandler<YouTubeApiKeyHandler>();
  133. services.AddHttpClient("PubSubHub", client =>
  134. {
  135. client.Timeout = TimeSpan.FromSeconds(15);
  136. });
  137. services.AddHttpClient("YouTubeFeed", client =>
  138. {
  139. client.Timeout = TimeSpan.FromSeconds(10);
  140. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/atom+xml"));
  141. });
  142. services.AddHttpClient<IGoogleOAuthService, GoogleOAuthService>();
  143. services.AddHttpClient<ITossPaymentService, TossPaymentService>(client =>
  144. {
  145. client.Timeout = TimeSpan.FromSeconds(60); // 토스 승인 API 권장 타임아웃 — 짧으면 통신 불명(대사 대상)만 늘어난다
  146. });
  147. services.AddSingleton<IYouTubeApiService, YouTubeApiService>();
  148. services.AddSingleton<IYouTubeChannelCache, YouTubeChannelCache>();
  149. services.AddSingleton<IYouTubeLiveStateStore, YouTubeLiveStateStore>();
  150. services.AddSingleton<YouTubeLiveChatService>();
  151. services.AddSingleton<IYouTubeLiveChatService>(sp => sp.GetRequiredService<YouTubeLiveChatService>());
  152. services.AddSingleton<YouTubePubSubService>();
  153. services.AddSingleton<IYouTubePubSubService>(sp => sp.GetRequiredService<YouTubePubSubService>());
  154. services.AddSingleton<IYouTubeFeedPoller, YouTubeFeedPoller>();
  155. // Notification
  156. services.AddScoped<INotificationService, Notification.NotificationService>();
  157. // Feed broadcaster (SignalR)
  158. services.AddScoped<IFeedBroadcaster, Hubs.FeedBroadcaster>();
  159. // Channel status broadcaster (라이브 시작/종료/시청자 수 → AppHub 브로드캐스트)
  160. services.AddSingleton<IChannelStatusBroadcaster, Hubs.ChannelStatusBroadcaster>();
  161. return services;
  162. }
  163. // Web.Api 전용 백그라운드 서비스 (Admin에서 중복 실행되면 quota 2배/폴링 2번 문제)
  164. // appsettings.json BackgroundJobs 섹션으로 개별 토글 (기본 모두 true). 진단용 A/B 테스트에 사용
  165. private static IServiceCollection AddBackgroundServices(this IServiceCollection services, IConfiguration configuration)
  166. {
  167. // Features:Channel OFF → YouTube/채널 백그라운드 서비스 전체 미등록 (코드 보존, 기능 노출 0)
  168. var features = configuration.GetSection("Features").Get<AppSettings.FeaturesSection>() ?? new AppSettings.FeaturesSection();
  169. if (!features.Channel)
  170. {
  171. return services;
  172. }
  173. var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
  174. if (bg.LiveChat)
  175. {
  176. services.AddHostedService(sp => sp.GetRequiredService<YouTubeLiveChatService>());
  177. }
  178. if (bg.PubSubRenewal)
  179. {
  180. services.AddHostedService<YouTubePubSubRenewalService>();
  181. }
  182. if (bg.FeedPolling)
  183. {
  184. services.AddHostedService<YouTubeFeedPollingService>();
  185. }
  186. if (bg.LiveViewerPoller)
  187. {
  188. services.AddHostedService<YouTubeLiveViewerPoller>();
  189. }
  190. if (bg.ChannelCacheRefresh)
  191. {
  192. services.AddHostedService<YouTubeChannelCacheRefreshService>();
  193. }
  194. if (bg.YouTubeDailyAggregator)
  195. {
  196. services.AddHostedService<YouTubeDailyAggregatorService>();
  197. }
  198. if (bg.YouTubeStaleDataPurge)
  199. {
  200. services.AddHostedService<YouTubeStaleDataPurgeService>();
  201. }
  202. return services;
  203. }
  204. // 결제 자동 대사 배치 (Toss NeedsReconciliation 재확인) — Features:Channel 게이트 밖 별도 등록, Web.Api 전용.
  205. // BackgroundJobs:PaymentReconcile 플래그로 토글 (기본 true — 대상 없으면 PG 호출 없이 skip)
  206. private static IServiceCollection AddPaymentBackgroundServices(this IServiceCollection services, IConfiguration configuration)
  207. {
  208. var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
  209. if (bg.PaymentReconcile)
  210. {
  211. services.AddHostedService<PaymentReconcileService>();
  212. }
  213. return services;
  214. }
  215. // 주식 데이터 수집 배치 (개미투자 D1) — Features:Channel 게이트 밖 별도 등록.
  216. // StockData 섹션 플래그로 개별 토글 (기본 모두 false — API 키 발급/운영 결정 후 활성화)
  217. private static IServiceCollection AddStockDataServices(this IServiceCollection services, IConfiguration configuration)
  218. {
  219. services.AddHttpClient(DataGoKrHttp.ClientName, client =>
  220. {
  221. client.Timeout = TimeSpan.FromSeconds(30);
  222. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  223. });
  224. // KRX OpenAPI(data-dbg.krx.co.kr) 지수 수집 클라이언트 — AUTH_KEY 헤더는 요청 단위로 부여 (KrxCoKrHttp)
  225. services.AddHttpClient(KrxCoKrHttp.ClientName, client =>
  226. {
  227. client.Timeout = TimeSpan.FromSeconds(30);
  228. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  229. });
  230. var stockData = configuration.GetSection("StockData").Get<AppSettings.StockDataSection>() ?? new AppSettings.StockDataSection();
  231. if (stockData.MasterSync)
  232. {
  233. services.AddHostedService<StockMasterSyncService>();
  234. }
  235. if (stockData.DailyPriceSync)
  236. {
  237. services.AddHostedService<DailyPriceSyncService>();
  238. }
  239. // 지수(시장) 일별시세 수집 (KRX OpenAPI) — KRXCoKr:IndexSync 플래그 (기본 false). KOSPI/KOSDAQ/KRX + 파생상품지수 한 배치
  240. var krx = configuration.GetSection("KRXCoKr").Get<AppSettings.KRXCoKrSection>() ?? new AppSettings.KRXCoKrSection();
  241. if (krx.IndexSync)
  242. {
  243. services.AddHostedService<IndexPriceSyncService>();
  244. }
  245. // 채권지수 일별시세 수집 (KRX OpenAPI idx/bon_dd_trd) — KRXCoKr:BondIndexSync 플래그 (기본 false). 응답 shape 이 달라 별도 배치. KRXCoKr HttpClient 재사용
  246. if (krx.BondIndexSync)
  247. {
  248. services.AddHostedService<BondIndexPriceSyncService>();
  249. }
  250. // 주식(종목) 마스터 + 일별매매 수집 (KRX OpenAPI) — KRXCoKr:StockSync 플래그 (기본 false). KRXCoKr HttpClient 재사용
  251. if (krx.StockSync)
  252. {
  253. services.AddHostedService<KrxStockMasterSyncService>();
  254. services.AddHostedService<KrxDailyPriceSyncService>();
  255. }
  256. // 증권상품(ETF/ETN/ELW) 일별매매 수집 (KRX OpenAPI) — KRXCoKr:EtpSync 플래그 (기본 false). KRXCoKr HttpClient 재사용
  257. if (krx.EtpSync)
  258. {
  259. services.AddHostedService<KrxEtpSyncService>();
  260. }
  261. // 신주인수권증권/증서 일별매매 수집 (KRX OpenAPI) — KRXCoKr:WarrantSync 플래그 (기본 false). KRXCoKr HttpClient 재사용
  262. if (krx.WarrantSync)
  263. {
  264. services.AddHostedService<KrxWarrantSyncService>();
  265. }
  266. // 채권(국채전문유통/일반채권/소액채권) 일별매매 수집 (KRX OpenAPI) — KRXCoKr:BondSync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
  267. if (krx.BondSync)
  268. {
  269. services.AddHostedService<KrxBondSyncService>();
  270. }
  271. // 파생상품(선물 3 + 옵션 3) 일별매매 수집 (KRX OpenAPI drv) — KRXCoKr:DerivativeSync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
  272. if (krx.DerivativeSync)
  273. {
  274. services.AddHostedService<KrxDerivativeSyncService>();
  275. }
  276. // 모의투자 체결·스냅샷 배치 (d4 M2) — BackgroundJobs:PaperFill 플래그 (기본 false). Web.Api 전용.
  277. var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
  278. if (bg.PaperFill)
  279. {
  280. services.AddHostedService<PaperFillService>();
  281. }
  282. // 예측 채점 배치 (d2 M4) — BackgroundJobs:PredictionSettlement 플래그 (기본 false). Web.Api 전용.
  283. if (bg.PredictionSettlement)
  284. {
  285. services.AddHostedService<PredictionSettlementService>();
  286. }
  287. return services;
  288. }
  289. /**
  290. * ========================================================================================================================================================================================================
  291. * ========================================================================================================================================================================================================
  292. */
  293. // Admin 전용 — 백그라운드 서비스는 포함하지 않음 (Web.Api에서만 돌아야 함)
  294. // 메일은 즉시 SMTP 발송 (DirectMailService)
  295. public static IServiceCollection AddAdminInfrastructure(this IServiceCollection services, IConfiguration configuration)
  296. {
  297. services.AddScoped<IMailService, DirectMailService>();
  298. return services.AddDatabase(configuration).AddRedis(configuration).AddCommonServices(configuration).AddHealthChecks(configuration);
  299. }
  300. /**
  301. * ========================================================================================================================================================================================================
  302. * ========================================================================================================================================================================================================
  303. */
  304. // API 전용 — 공용 서비스 + 백그라운드 서비스 모두 포함
  305. // 메일은 EmailLog 큐에 적재 (QueuedMailService) — MailWorker가 별도로 폴링하여 SMTP 송신
  306. public static IServiceCollection AddApiInfrastructure(this IServiceCollection services, IConfiguration configuration)
  307. {
  308. services.AddScoped<IMailService, QueuedMailService>();
  309. return services.AddDatabase(configuration).AddRedis(configuration).AddApiAuthentication(configuration).AddCommonServices(configuration).AddBackgroundServices(configuration).AddPaymentBackgroundServices(configuration).AddStockDataServices(configuration).AddHealthChecks(configuration);
  310. }
  311. private static IServiceCollection AddApiAuthentication(this IServiceCollection services, IConfiguration configuration)
  312. {
  313. var settings = configuration.Get<AppSettings>()!;
  314. // 인증 정책- JWT Bearer
  315. services.AddAuthentication(options =>
  316. {
  317. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  318. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  319. })
  320. .AddJwtBearer(options =>
  321. {
  322. options.RequireHttpsMetadata = false;
  323. options.MapInboundClaims = false;
  324. options.TokenValidationParameters = new TokenValidationParameters
  325. {
  326. ValidateIssuer = true,
  327. ValidateAudience = true,
  328. ValidateLifetime = true,
  329. ValidateIssuerSigningKey = true,
  330. ValidIssuer = settings.JWT.Issuer,
  331. ValidAudience = settings.JWT.Audience,
  332. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.JWT.SecretKey)),
  333. ClockSkew = TimeSpan.Zero
  334. };
  335. options.Events = new JwtBearerEvents
  336. {
  337. OnMessageReceived = context =>
  338. {
  339. var accessToken = context.Request.Query["access_token"];
  340. var path = context.HttpContext.Request.Path;
  341. if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
  342. {
  343. context.Token = accessToken;
  344. }
  345. return Task.CompletedTask;
  346. }
  347. };
  348. });
  349. services.AddAuthorization();
  350. // Identity Core (Admin Handler의 UserManager/RoleManager 의존 해소용)
  351. services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
  352. return services;
  353. }
  354. }