DependencyInjection.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 Application.Helpers;
  14. using Infrastructure.Authentication;
  15. using Infrastructure.Crypto;
  16. using Infrastructure.Payment;
  17. using Infrastructure.Forum;
  18. using Infrastructure.Cache;
  19. using Infrastructure.Chat;
  20. using Infrastructure.Messaging.Email;
  21. using Infrastructure.Persistence;
  22. using Infrastructure.Persistence.Identity;
  23. using Infrastructure.StockData;
  24. using Infrastructure.Storage;
  25. using Infrastructure.YouTube;
  26. using Microsoft.AspNetCore.Authentication;
  27. using Microsoft.AspNetCore.Authentication.JwtBearer;
  28. using Microsoft.AspNetCore.DataProtection;
  29. using Microsoft.AspNetCore.Identity;
  30. using Microsoft.AspNetCore.Identity.UI.Services;
  31. using Microsoft.EntityFrameworkCore;
  32. using Microsoft.EntityFrameworkCore.Diagnostics;
  33. using Microsoft.Extensions.Configuration;
  34. using Microsoft.Extensions.DependencyInjection;
  35. using Microsoft.Extensions.Options;
  36. using Microsoft.IdentityModel.Tokens;
  37. using SharedKernel;
  38. using SharedKernel.Storage;
  39. using StackExchange.Redis;
  40. using System.Text;
  41. namespace Infrastructure;
  42. public static class DependencyInjection
  43. {
  44. // SQL Server
  45. private static IServiceCollection AddDatabase(this IServiceCollection services, IConfiguration configuration)
  46. {
  47. var dbConn = configuration.GetConnectionString("DefaultConnection");
  48. if (string.IsNullOrWhiteSpace(dbConn))
  49. {
  50. throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured.");
  51. }
  52. // Pooling: 매 request 마다 새 DbContext 생성 비용 제거. ChangeTracker 등 내부 상태는 풀 반환 시 자동 reset
  53. // ConfigureWarnings: EF 9+의 PendingModelChangesWarning을 무시 (snapshot 일관성 문제로 false-positive 발생, 마이그레이션은 별도 관리)
  54. void ConfigureAppDb(DbContextOptionsBuilder options) => options
  55. .UseSqlServer(dbConn)
  56. .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning));
  57. services.AddDbContextPool<AppDbContext>(ConfigureAppDb, poolSize: 128);
  58. services.AddDbContextPool<IdentityDbContext>(options => options
  59. .UseSqlServer(dbConn)
  60. .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning)), poolSize: 64);
  61. services.AddScoped<IAppDbContext>(sp => sp.GetRequiredService<AppDbContext>());
  62. // Phase 1.5: out-of-band 커밋(대사 로그·동시성 재시도)용 풀링 팩토리.
  63. // 내부 등록이 전부 TryAdd 라 위 AddDbContextPool 과 같은 옵션·풀을 공유하며 중복 등록 없이 공존한다.
  64. services.AddPooledDbContextFactory<AppDbContext>(ConfigureAppDb, poolSize: 128);
  65. services.AddSingleton<IAppDbContextFactory, AppDbContextFactory>();
  66. return services;
  67. }
  68. // Redis Server
  69. public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
  70. {
  71. var settings = configuration.Get<AppSettings>()!;
  72. var redis = ConnectionMultiplexer.Connect(settings.Redis.DefaultConnection);
  73. services.AddSingleton<IConnectionMultiplexer>(redis);
  74. services.AddDataProtection()
  75. .SetApplicationName(settings.App.Name)
  76. .PersistKeysToStackExchangeRedis(redis, settings.Redis.DataProtectionKey)
  77. .ProtectKeysWithDpapi(protectToLocalMachine: true) // key를 암호화하여 저장 (로컬 머신에서만 복호화 가능, 서버간 공유 불가)
  78. .SetDefaultKeyLifetime(settings.Redis.DefaultKeyLifetime); // 기본 90일 주기
  79. // Distributed Cache 설정
  80. services.AddStackExchangeRedisCache(options =>
  81. {
  82. options.Configuration = settings.Redis.DefaultConnection;
  83. options.InstanceName = settings.Redis.CachePrefix;
  84. });
  85. return services;
  86. }
  87. private static IServiceCollection AddHealthChecks(this IServiceCollection services, IConfiguration configuration)
  88. {
  89. var settings = configuration.Get<AppSettings>()!;
  90. services.AddHealthChecks().AddSqlServer(settings.ConnectionStrings.DefaultConnection).AddRedis(settings.Redis.DefaultConnection);
  91. return services;
  92. }
  93. // Admin/Api 둘 다 필요한 공용 서비스 (singleton/transient/scoped, HttpClient)
  94. private static IServiceCollection AddCommonServices(this IServiceCollection services, IConfiguration configuration)
  95. {
  96. // 파일 저장 위치 옵션 (deploy 영향 받지 않는 외부 경로 권장)
  97. services.Configure<StorageOptions>(configuration.GetSection(StorageOptions.SectionName));
  98. services.AddSingleton<IJwtTokenProvider, JwtTokenProvider>();
  99. services.AddSingleton<ILegacyPasswordVerifier, BcryptLegacyPasswordVerifier>();
  100. services.AddSingleton<ICacheService, RedisCacheService>();
  101. services.AddSingleton<IFieldEncryptor, AesGcmFieldEncryptor>();
  102. services.AddTransient<IEmailSender, IdentityEmailSender>();
  103. services.AddScoped<IFileStorage, LocalFileStorage>();
  104. services.AddScoped<IEditorImageService, EditorImageService>();
  105. services.AddScoped<IIdentityUserReader, IdentityUserReader>();
  106. services.AddScoped<IIdentityUserWriter, IdentityUserWriter>();
  107. services.AddScoped<IIdentityRoleReader, IdentityRoleReader>();
  108. services.AddScoped<IIdentityRoleWriter, IdentityRoleWriter>();
  109. services.AddSingleton<IChatMessageStore, RedisChatMessageStore>();
  110. services.AddSingleton<IChatConnectionTracker, RedisChatConnectionTracker>();
  111. services.AddSingleton<IChatLeaderboard, RedisChatLeaderboard>();
  112. services.AddSingleton<Application.Abstractions.Paper.IPaperLeaderboardCache, Paper.PaperLeaderboardCache>();
  113. services.AddSingleton<Application.Abstractions.Stocks.IStockBoardTrendingCache, Stocks.RedisStockBoardTrendingCache>();
  114. services.AddSingleton<IChatRewardHook, RewardChatHook>(); // D3 M2 실구현 — ChatExpConfig 수치를 RewardService 로 지급 (d0 §2.2)
  115. services.AddSingleton<IPresenceTracker, Hubs.PresenceTracker>();
  116. services.AddSingleton<IVisitorTracker, Hubs.RedisVisitorTracker>();
  117. services.AddScoped<IBoardPermissionService, BoardPermissionService>();
  118. services.AddHttpClient<IGoogleTokenValidator, GoogleTokenValidator>();
  119. // 소셜 로그인 provider (개미투자 D5 — Naver/Kakao authorization code). 핸들러가 IEnumerable 에서 이름으로 해석
  120. services.AddHttpClient<NaverAuthProvider>();
  121. services.AddHttpClient<KakaoAuthProvider>();
  122. services.AddTransient<ISocialAuthProvider>(sp => sp.GetRequiredService<NaverAuthProvider>());
  123. services.AddTransient<ISocialAuthProvider>(sp => sp.GetRequiredService<KakaoAuthProvider>());
  124. // YouTube & Google OAuth (HttpClients + singletons — Admin에서도 "API 키 테스트" 등에 쓰므로 공용)
  125. services.AddSingleton<IYouTubeApiKeyProvider, YouTubeApiKeyProvider>();
  126. services.AddTransient<YouTubeApiKeyHandler>();
  127. services.AddTransient<IYouTubeApiConnectionTester, YouTubeApiConnectionTester>();
  128. services.AddHttpClient("YouTubeApi", client =>
  129. {
  130. client.Timeout = TimeSpan.FromSeconds(15);
  131. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  132. })
  133. .AddHttpMessageHandler<YouTubeApiKeyHandler>();
  134. services.AddHttpClient("PubSubHub", client =>
  135. {
  136. client.Timeout = TimeSpan.FromSeconds(15);
  137. });
  138. services.AddHttpClient("YouTubeFeed", client =>
  139. {
  140. client.Timeout = TimeSpan.FromSeconds(10);
  141. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/atom+xml"));
  142. });
  143. services.AddHttpClient<IGoogleOAuthService, GoogleOAuthService>();
  144. services.AddHttpClient<ITossPaymentService, TossPaymentService>(client =>
  145. {
  146. client.Timeout = TimeSpan.FromSeconds(60); // 토스 승인 API 권장 타임아웃 — 짧으면 통신 불명(대사 대상)만 늘어난다
  147. });
  148. services.AddSingleton<IYouTubeApiService, YouTubeApiService>();
  149. services.AddSingleton<IYouTubeChannelCache, YouTubeChannelCache>();
  150. services.AddSingleton<IYouTubeLiveStateStore, YouTubeLiveStateStore>();
  151. services.AddSingleton<YouTubeLiveChatService>();
  152. services.AddSingleton<IYouTubeLiveChatService>(sp => sp.GetRequiredService<YouTubeLiveChatService>());
  153. services.AddSingleton<YouTubePubSubService>();
  154. services.AddSingleton<IYouTubePubSubService>(sp => sp.GetRequiredService<YouTubePubSubService>());
  155. services.AddSingleton<IYouTubeFeedPoller, YouTubeFeedPoller>();
  156. // Notification
  157. services.AddScoped<INotificationService, Notification.NotificationService>();
  158. // Feed broadcaster (SignalR)
  159. services.AddScoped<IFeedBroadcaster, Hubs.FeedBroadcaster>();
  160. // Channel status broadcaster (라이브 시작/종료/시청자 수 → AppHub 브로드캐스트)
  161. services.AddSingleton<IChannelStatusBroadcaster, Hubs.ChannelStatusBroadcaster>();
  162. return services;
  163. }
  164. // Web.Api 전용 백그라운드 서비스 (Admin에서 중복 실행되면 quota 2배/폴링 2번 문제)
  165. // appsettings.json BackgroundJobs 섹션으로 개별 토글 (기본 모두 true). 진단용 A/B 테스트에 사용
  166. private static IServiceCollection AddBackgroundServices(this IServiceCollection services, IConfiguration configuration)
  167. {
  168. // Features:Channel OFF → YouTube/채널 백그라운드 서비스 전체 미등록 (코드 보존, 기능 노출 0)
  169. var features = configuration.GetSection("Features").Get<AppSettings.FeaturesSection>() ?? new AppSettings.FeaturesSection();
  170. if (!features.Channel)
  171. {
  172. return services;
  173. }
  174. var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
  175. if (bg.LiveChat)
  176. {
  177. services.AddHostedService(sp => sp.GetRequiredService<YouTubeLiveChatService>());
  178. }
  179. if (bg.PubSubRenewal)
  180. {
  181. services.AddHostedService<YouTubePubSubRenewalService>();
  182. }
  183. if (bg.FeedPolling)
  184. {
  185. services.AddHostedService<YouTubeFeedPollingService>();
  186. }
  187. if (bg.LiveViewerPoller)
  188. {
  189. services.AddHostedService<YouTubeLiveViewerPoller>();
  190. }
  191. if (bg.ChannelCacheRefresh)
  192. {
  193. services.AddHostedService<YouTubeChannelCacheRefreshService>();
  194. }
  195. if (bg.YouTubeDailyAggregator)
  196. {
  197. services.AddHostedService<YouTubeDailyAggregatorService>();
  198. }
  199. if (bg.YouTubeStaleDataPurge)
  200. {
  201. services.AddHostedService<YouTubeStaleDataPurgeService>();
  202. }
  203. return services;
  204. }
  205. // 결제 자동 대사 배치 (Toss NeedsReconciliation 재확인) — Features:Channel 게이트 밖 별도 등록, Web.Api 전용.
  206. // BackgroundJobs:PaymentReconcile 플래그로 토글 (기본 true — 대상 없으면 PG 호출 없이 skip)
  207. private static IServiceCollection AddPaymentBackgroundServices(this IServiceCollection services, IConfiguration configuration)
  208. {
  209. var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
  210. if (bg.PaymentReconcile)
  211. {
  212. services.AddHostedService<PaymentReconcileService>();
  213. }
  214. return services;
  215. }
  216. // 주식 데이터 수집 배치 (개미투자 D1) — Features:Channel 게이트 밖 별도 등록.
  217. // StockData 섹션 플래그로 개별 토글 (기본 모두 false — API 키 발급/운영 결정 후 활성화)
  218. private static IServiceCollection AddStockDataServices(this IServiceCollection services, IConfiguration configuration)
  219. {
  220. services.AddHttpClient(DataGoKrHttp.ClientName, client =>
  221. {
  222. client.Timeout = TimeSpan.FromSeconds(30);
  223. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  224. });
  225. // KRX OpenAPI(data-dbg.krx.co.kr) 지수 수집 클라이언트 — AUTH_KEY 헤더는 요청 단위로 부여 (KrxCoKrHttp)
  226. services.AddHttpClient(KrxCoKrHttp.ClientName, client =>
  227. {
  228. client.Timeout = TimeSpan.FromSeconds(30);
  229. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  230. });
  231. // OpenDART(opendart.fss.or.kr) 공시 수집 클라이언트 — 인증은 URL query param crtfc_key (요청 단위, OpenDartHttp)
  232. services.AddHttpClient(OpenDartHttp.ClientName, client =>
  233. {
  234. client.Timeout = TimeSpan.FromSeconds(30);
  235. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  236. });
  237. // 한국수출입은행(koreaexim.go.kr) 거시·환율 수집 클라이언트 — 인증은 URL query param authkey (요청 단위, KoreaEximHttp)
  238. services.AddHttpClient(KoreaEximHttp.ClientName, client =>
  239. {
  240. client.Timeout = TimeSpan.FromSeconds(30);
  241. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  242. });
  243. // SEIBro OpenAPI(seibro.or.kr) 수집 클라이언트 — 인증은 URL query param key (요청 단위, SeibroHttp). 응답은 XML
  244. services.AddHttpClient(SeibroHttp.ClientName, client =>
  245. {
  246. client.Timeout = TimeSpan.FromSeconds(30);
  247. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
  248. });
  249. // SEIBro 카테고리별 일일 호출 예산 트래커 — 같은 카테고리 배치들이 하나의 카운터를 공유 (in-memory, KST 자정 롤오버)
  250. services.AddSingleton(_ => new SeibroQuota());
  251. var stockData = configuration.GetSection("StockData").Get<AppSettings.StockDataSection>() ?? new AppSettings.StockDataSection();
  252. if (stockData.MasterSync)
  253. {
  254. services.AddHostedService<StockMasterSyncService>();
  255. }
  256. if (stockData.DailyPriceSync)
  257. {
  258. services.AddHostedService<DailyPriceSyncService>();
  259. }
  260. // 지수(시장) 일별시세 수집 (KRX OpenAPI) — KRXCoKr:IndexSync 플래그 (기본 false). KOSPI/KOSDAQ/KRX + 파생상품지수 한 배치
  261. var krx = configuration.GetSection("KRXCoKr").Get<AppSettings.KRXCoKrSection>() ?? new AppSettings.KRXCoKrSection();
  262. if (krx.IndexSync)
  263. {
  264. services.AddHostedService<IndexPriceSyncService>();
  265. }
  266. // 채권지수 일별시세 수집 (KRX OpenAPI idx/bon_dd_trd) — KRXCoKr:BondIndexSync 플래그 (기본 false). 응답 shape 이 달라 별도 배치. KRXCoKr HttpClient 재사용
  267. if (krx.BondIndexSync)
  268. {
  269. services.AddHostedService<BondIndexPriceSyncService>();
  270. }
  271. // 주식(종목) 마스터 + 일별매매 수집 (KRX OpenAPI) — KRXCoKr:StockSync 플래그 (기본 false). KRXCoKr HttpClient 재사용
  272. if (krx.StockSync)
  273. {
  274. services.AddHostedService<KrxStockMasterSyncService>();
  275. services.AddHostedService<KrxDailyPriceSyncService>();
  276. }
  277. // 증권상품(ETF/ETN/ELW) 일별매매 수집 (KRX OpenAPI) — KRXCoKr:EtpSync 플래그 (기본 false). KRXCoKr HttpClient 재사용
  278. if (krx.EtpSync)
  279. {
  280. services.AddHostedService<KrxEtpSyncService>();
  281. }
  282. // 신주인수권증권/증서 일별매매 수집 (KRX OpenAPI) — KRXCoKr:WarrantSync 플래그 (기본 false). KRXCoKr HttpClient 재사용
  283. if (krx.WarrantSync)
  284. {
  285. services.AddHostedService<KrxWarrantSyncService>();
  286. }
  287. // 채권(국채전문유통/일반채권/소액채권) 일별매매 수집 (KRX OpenAPI) — KRXCoKr:BondSync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
  288. if (krx.BondSync)
  289. {
  290. services.AddHostedService<KrxBondSyncService>();
  291. }
  292. // 파생상품(선물 3 + 옵션 3) 일별매매 수집 (KRX OpenAPI drv) — KRXCoKr:DerivativeSync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
  293. if (krx.DerivativeSync)
  294. {
  295. services.AddHostedService<KrxDerivativeSyncService>();
  296. }
  297. // 일반상품(석유·금·배출권) 일별매매 수집 (KRX OpenAPI gen) — KRXCoKr:CommoditySync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
  298. if (krx.CommoditySync)
  299. {
  300. services.AddHostedService<KrxCommoditySyncService>();
  301. }
  302. // ESG 데이터(ESG 증권상품 + ESG 지수 + 사회책임투자채권) 수집 (KRX OpenAPI esg) — KRXCoKr:EsgSync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
  303. if (krx.EsgSync)
  304. {
  305. services.AddHostedService<KrxEsgSyncService>();
  306. }
  307. // 전자공시(DART) 공시 목록 수집 (OpenDART list.json) — OpenDart:DisclosureSync 플래그 (기본 false). 접수일 최근 N일 페이징. OpenDart HttpClient 사용
  308. var dart = configuration.GetSection("OpenDart").Get<AppSettings.OpenDartSection>() ?? new AppSettings.OpenDartSection();
  309. if (dart.DisclosureSync)
  310. {
  311. services.AddHostedService<DisclosureSyncService>();
  312. }
  313. // 거시·환율 수집 (한국수출입은행 AP01 환율 + AP02 대출금리 + AP03 국제금리) — KoreaExim:MacroSync 플래그 (기본 false). KrxBackfill 로 최근 N일 백필. KoreaExim HttpClient 사용
  314. var koreaExim = configuration.GetSection("KoreaExim").Get<AppSettings.KoreaEximSection>() ?? new AppSettings.KoreaEximSection();
  315. if (koreaExim.MacroSync)
  316. {
  317. services.AddHostedService<MacroDataSyncService>();
  318. }
  319. // SEIBro 발행회사번호(조인키) 부트스트랩 + 종목 보강 (getShotnByMart/getStkStatInfo) — Seibro:IssuerSync 플래그 (기본 false). Seibro HttpClient + SeibroQuota 사용
  320. var seibro = configuration.GetSection("Seibro").Get<AppSettings.SeibroSection>() ?? new AppSettings.SeibroSection();
  321. if (seibro.IssuerSync)
  322. {
  323. services.AddHostedService<SeibroIssuerSyncService>();
  324. }
  325. // SEIBro 배당·권리 수집 (getDivSchedulInfo/getDivInfo/getStddtInfo) — Seibro:DividendSync 플래그 (기본 false). Corp 카테고리 예산 공유
  326. if (seibro.DividendSync)
  327. {
  328. services.AddHostedService<SeibroDividendSyncService>();
  329. }
  330. // SEIBro 수급 이벤트 수집 (대차·보호예수·증감·유통변경·비상장) — Seibro:SupplySync 플래그 (기본 false). Stock 카테고리 예산 공유
  331. if (seibro.SupplySync)
  332. {
  333. services.AddHostedService<SeibroSupplySyncService>();
  334. }
  335. // SEIBro 기업행위·총회 수집 (총회·상호변경·대금·단주·CB/BW 행사) — Seibro:CorpActionSync 플래그 (기본 false). 총회·상호·대금·단주=Corp 예산, CB/BW 행사=Stock 예산 공유
  336. if (seibro.CorpActionSync)
  337. {
  338. services.AddHostedService<SeibroCorpActionSyncService>();
  339. }
  340. // 모의투자 체결·스냅샷 배치 (d4 M2) — BackgroundJobs:PaperFill 플래그 (기본 false). Web.Api 전용.
  341. var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
  342. if (bg.PaperFill)
  343. {
  344. services.AddHostedService<PaperFillService>();
  345. }
  346. // 예측 채점 배치 (d2 M4) — BackgroundJobs:PredictionSettlement 플래그 (기본 false). Web.Api 전용.
  347. if (bg.PredictionSettlement)
  348. {
  349. services.AddHostedService<PredictionSettlementService>();
  350. }
  351. // 장전 브리핑 자동 발행 배치 (d2 M3) — BackgroundJobs:DailyBriefing 플래그 (기본 false, 07:30 KST). Web.Api 전용.
  352. if (bg.DailyBriefing)
  353. {
  354. services.AddHostedService<DailyBriefingPublisher>();
  355. }
  356. return services;
  357. }
  358. /**
  359. * ========================================================================================================================================================================================================
  360. * ========================================================================================================================================================================================================
  361. */
  362. // Admin 전용 — 백그라운드 서비스는 포함하지 않음 (Web.Api에서만 돌아야 함)
  363. // 메일은 즉시 SMTP 발송 (DirectMailService)
  364. public static IServiceCollection AddAdminInfrastructure(this IServiceCollection services, IConfiguration configuration)
  365. {
  366. services.AddScoped<IMailService, DirectMailService>();
  367. return services.AddDatabase(configuration).AddRedis(configuration).AddCommonServices(configuration).AddHealthChecks(configuration);
  368. }
  369. /**
  370. * ========================================================================================================================================================================================================
  371. * ========================================================================================================================================================================================================
  372. */
  373. // API 전용 — 공용 서비스 + 백그라운드 서비스 모두 포함
  374. // 메일은 EmailLog 큐에 적재 (QueuedMailService) — MailWorker가 별도로 폴링하여 SMTP 송신
  375. public static IServiceCollection AddApiInfrastructure(this IServiceCollection services, IConfiguration configuration)
  376. {
  377. services.AddScoped<IMailService, QueuedMailService>();
  378. return services.AddDatabase(configuration).AddRedis(configuration).AddApiAuthentication(configuration).AddCommonServices(configuration).AddBackgroundServices(configuration).AddPaymentBackgroundServices(configuration).AddStockDataServices(configuration).AddHealthChecks(configuration);
  379. }
  380. private static IServiceCollection AddApiAuthentication(this IServiceCollection services, IConfiguration configuration)
  381. {
  382. var settings = configuration.Get<AppSettings>()!;
  383. // 인증 정책- JWT Bearer
  384. services.AddAuthentication(options =>
  385. {
  386. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  387. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  388. })
  389. .AddJwtBearer(options =>
  390. {
  391. options.RequireHttpsMetadata = false;
  392. options.MapInboundClaims = false;
  393. options.TokenValidationParameters = new TokenValidationParameters
  394. {
  395. ValidateIssuer = true,
  396. ValidateAudience = true,
  397. ValidateLifetime = true,
  398. ValidateIssuerSigningKey = true,
  399. ValidIssuer = settings.JWT.Issuer,
  400. ValidAudience = settings.JWT.Audience,
  401. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.JWT.SecretKey)),
  402. ClockSkew = TimeSpan.Zero
  403. };
  404. options.Events = new JwtBearerEvents
  405. {
  406. OnMessageReceived = context =>
  407. {
  408. var accessToken = context.Request.Query["access_token"];
  409. var path = context.HttpContext.Request.Path;
  410. if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
  411. {
  412. context.Token = accessToken;
  413. }
  414. return Task.CompletedTask;
  415. }
  416. };
  417. });
  418. services.AddAuthorization();
  419. // Identity Core (Admin Handler의 UserManager/RoleManager 의존 해소용)
  420. services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
  421. return services;
  422. }
  423. }