DependencyInjection.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. // KOSIS(kosis.kr) 거시경제지표 수집 클라이언트 — 인증은 URL query param apiKey (요청 단위, KosisHttp). 응답은 JSON
  244. services.AddHttpClient(KosisHttp.ClientName, client =>
  245. {
  246. client.Timeout = TimeSpan.FromSeconds(30);
  247. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  248. });
  249. // SEIBro OpenAPI(seibro.or.kr) 수집 클라이언트 — 인증은 URL query param key (요청 단위, SeibroHttp). 응답은 XML
  250. services.AddHttpClient(SeibroHttp.ClientName, client =>
  251. {
  252. client.Timeout = TimeSpan.FromSeconds(30);
  253. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
  254. });
  255. // Stooq(stooq.com) 무인증 CSV 시세 클라이언트 — (구) 세계지수/종목 수집. Stooq 봇차단(2026-07)으로 미사용, 등록만 보존
  256. services.AddHttpClient(StooqHttp.ClientName, client =>
  257. {
  258. client.Timeout = TimeSpan.FromSeconds(30);
  259. });
  260. // Yahoo Finance v8 chart 무인증 JSON 클라이언트 — 세계지수·종목 수집 (YahooFinanceHttp). UA 필수(없으면 거부). Stooq 대체
  261. services.AddHttpClient(YahooFinanceHttp.ClientName, client =>
  262. {
  263. client.Timeout = TimeSpan.FromSeconds(30);
  264. client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0");
  265. });
  266. // SEIBro 카테고리별 일일 호출 예산 트래커 — 같은 카테고리 배치들이 하나의 카운터를 공유 (in-memory, KST 자정 롤오버)
  267. services.AddSingleton(_ => new SeibroQuota());
  268. var stockData = configuration.GetSection("StockData").Get<AppSettings.StockDataSection>() ?? new AppSettings.StockDataSection();
  269. if (stockData.MasterSync)
  270. {
  271. services.AddHostedService<StockMasterSyncService>();
  272. }
  273. if (stockData.DailyPriceSync)
  274. {
  275. services.AddHostedService<DailyPriceSyncService>();
  276. }
  277. // 지수(시장) 일별시세 수집 (KRX OpenAPI) — KRXCoKr:IndexSync 플래그 (기본 false). KOSPI/KOSDAQ/KRX + 파생상품지수 한 배치
  278. var krx = configuration.GetSection("KRXCoKr").Get<AppSettings.KRXCoKrSection>() ?? new AppSettings.KRXCoKrSection();
  279. if (krx.IndexSync)
  280. {
  281. services.AddHostedService<IndexPriceSyncService>();
  282. }
  283. // 채권지수 일별시세 수집 (KRX OpenAPI idx/bon_dd_trd) — KRXCoKr:BondIndexSync 플래그 (기본 false). 응답 shape 이 달라 별도 배치. KRXCoKr HttpClient 재사용
  284. if (krx.BondIndexSync)
  285. {
  286. services.AddHostedService<BondIndexPriceSyncService>();
  287. }
  288. // 주식(종목) 마스터 + 일별매매 수집 (KRX OpenAPI) — KRXCoKr:StockSync 플래그 (기본 false). KRXCoKr HttpClient 재사용
  289. if (krx.StockSync)
  290. {
  291. services.AddHostedService<KrxStockMasterSyncService>();
  292. services.AddHostedService<KrxDailyPriceSyncService>();
  293. }
  294. // 증권상품(ETF/ETN/ELW) 일별매매 수집 (KRX OpenAPI) — KRXCoKr:EtpSync 플래그 (기본 false). KRXCoKr HttpClient 재사용
  295. if (krx.EtpSync)
  296. {
  297. services.AddHostedService<KrxEtpSyncService>();
  298. }
  299. // 신주인수권증권/증서 일별매매 수집 (KRX OpenAPI) — KRXCoKr:WarrantSync 플래그 (기본 false). KRXCoKr HttpClient 재사용
  300. if (krx.WarrantSync)
  301. {
  302. services.AddHostedService<KrxWarrantSyncService>();
  303. }
  304. // 채권(국채전문유통/일반채권/소액채권) 일별매매 수집 (KRX OpenAPI) — KRXCoKr:BondSync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
  305. if (krx.BondSync)
  306. {
  307. services.AddHostedService<KrxBondSyncService>();
  308. }
  309. // 파생상품(선물 3 + 옵션 3) 일별매매 수집 (KRX OpenAPI drv) — KRXCoKr:DerivativeSync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
  310. if (krx.DerivativeSync)
  311. {
  312. services.AddHostedService<KrxDerivativeSyncService>();
  313. }
  314. // 일반상품(석유·금·배출권) 일별매매 수집 (KRX OpenAPI gen) — KRXCoKr:CommoditySync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
  315. if (krx.CommoditySync)
  316. {
  317. services.AddHostedService<KrxCommoditySyncService>();
  318. }
  319. // ESG 데이터(ESG 증권상품 + ESG 지수 + 사회책임투자채권) 수집 (KRX OpenAPI esg) — KRXCoKr:EsgSync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
  320. if (krx.EsgSync)
  321. {
  322. services.AddHostedService<KrxEsgSyncService>();
  323. }
  324. // 전자공시(DART) 공시 목록 수집 (OpenDART list.json) — OpenDart:DisclosureSync 플래그 (기본 false). 접수일 최근 N일 페이징. OpenDart HttpClient 사용
  325. var dart = configuration.GetSection("OpenDart").Get<AppSettings.OpenDartSection>() ?? new AppSettings.OpenDartSection();
  326. if (dart.DisclosureSync)
  327. {
  328. services.AddHostedService<DisclosureSyncService>();
  329. }
  330. // 거시·환율 수집 (한국수출입은행 AP01 환율 + AP02 대출금리 + AP03 국제금리) — KoreaExim:MacroSync 플래그 (기본 false). KrxBackfill 로 최근 N일 백필. KoreaExim HttpClient 사용
  331. var koreaExim = configuration.GetSection("KoreaExim").Get<AppSettings.KoreaEximSection>() ?? new AppSettings.KoreaEximSection();
  332. if (koreaExim.MacroSync)
  333. {
  334. services.AddHostedService<MacroDataSyncService>();
  335. }
  336. // 거시경제지표 수집 (KOSIS statisticsData.do — 고용률/실업률/취업자수/CPI/환율/수출액/수입액 7종) — Kosis:Sync 플래그 (기본 false). config Indicators 순회 upsert. Kosis HttpClient 사용
  337. var kosis = configuration.GetSection("Kosis").Get<AppSettings.KosisSection>() ?? new AppSettings.KosisSection();
  338. if (kosis.Sync)
  339. {
  340. services.AddHostedService<KosisSyncService>();
  341. }
  342. // SEIBro 발행회사번호(조인키) 부트스트랩 + 종목 보강 (getShotnByMart/getStkStatInfo) — Seibro:IssuerSync 플래그 (기본 false). Seibro HttpClient + SeibroQuota 사용
  343. var seibro = configuration.GetSection("Seibro").Get<AppSettings.SeibroSection>() ?? new AppSettings.SeibroSection();
  344. if (seibro.IssuerSync)
  345. {
  346. services.AddHostedService<SeibroIssuerSyncService>();
  347. }
  348. // SEIBro 배당·권리 수집 (getDivSchedulInfo/getDivInfo/getStddtInfo) — Seibro:DividendSync 플래그 (기본 false). Corp 카테고리 예산 공유
  349. if (seibro.DividendSync)
  350. {
  351. services.AddHostedService<SeibroDividendSyncService>();
  352. }
  353. // SEIBro 수급 이벤트 수집 (대차·보호예수·증감·유통변경·비상장) — Seibro:SupplySync 플래그 (기본 false). Stock 카테고리 예산 공유
  354. if (seibro.SupplySync)
  355. {
  356. services.AddHostedService<SeibroSupplySyncService>();
  357. }
  358. // SEIBro 기업행위·총회 수집 (총회·상호변경·대금·단주·CB/BW 행사) — Seibro:CorpActionSync 플래그 (기본 false). 총회·상호·대금·단주=Corp 예산, CB/BW 행사=Stock 예산 공유
  359. if (seibro.CorpActionSync)
  360. {
  361. services.AddHostedService<SeibroCorpActionSyncService>();
  362. }
  363. // SEIBro 채권·단기금융 수집 (발행·마스터·이자·조기상환·단기발행·CD/CP/전단채) — Seibro:BondSync 플래그 (기본 false). Bond 카테고리 예산 공유
  364. if (seibro.BondSync)
  365. {
  366. services.AddHostedService<SeibroBondSyncService>();
  367. }
  368. // SEIBro 파생결합증권 ELS/DLS 수집 (발행·마스터·기초자산·행사·상환조건·상환종목·미상환규모) — Seibro:DerivSync 플래그 (기본 false). Deriv 카테고리 예산 공유
  369. if (seibro.DerivSync)
  370. {
  371. services.AddHostedService<SeibroDerivSyncService>();
  372. }
  373. // SEIBro 외화증권 수집 (국가별 보관·결제 + 종목별 보관·결제) — Seibro:ForeignSync 플래그 (기본 false). Foreign 카테고리 예산 공유. ForeignIsins 빈 리스트면 종목별 대기
  374. if (seibro.ForeignSync)
  375. {
  376. services.AddHostedService<SeibroForeignSyncService>();
  377. }
  378. // 세계 주요국 증시지수 스냅샷 수집 (Stooq 무인증 CSV /q/l/) — WorldIndex:Enabled 플래그 (기본 false). 메인 세계지도 핀. 국내(코스피)는 IndexDailyPrice 에서 병합. Stooq HttpClient 사용
  379. var worldIndex = configuration.GetSection("WorldIndex").Get<AppSettings.WorldIndexSection>() ?? new AppSettings.WorldIndexSection();
  380. if (worldIndex.Enabled)
  381. {
  382. services.AddHostedService<WorldIndexSyncService>();
  383. }
  384. // 주요 종목·상품 시세 스냅샷 수집 (Stooq /q/l/ 거래량 포함) — MarketQuote:Enabled 플래그 (기본 false). 주요종목현황·상품선물 그리드. Stooq HttpClient 재사용
  385. var marketQuote = configuration.GetSection("MarketQuote").Get<AppSettings.MarketQuoteSection>() ?? new AppSettings.MarketQuoteSection();
  386. if (marketQuote.Enabled)
  387. {
  388. services.AddHostedService<MarketQuoteSyncService>();
  389. }
  390. // 모의투자 체결·스냅샷 배치 (d4 M2) — BackgroundJobs:PaperFill 플래그 (기본 false). Web.Api 전용.
  391. var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
  392. if (bg.PaperFill)
  393. {
  394. services.AddHostedService<PaperFillService>();
  395. }
  396. // 예측 채점 배치 (d2 M4) — BackgroundJobs:PredictionSettlement 플래그 (기본 false). Web.Api 전용.
  397. if (bg.PredictionSettlement)
  398. {
  399. services.AddHostedService<PredictionSettlementService>();
  400. }
  401. // 장전 브리핑 자동 발행 배치 (d2 M3) — BackgroundJobs:DailyBriefing 플래그 (기본 false, 07:30 KST). Web.Api 전용.
  402. if (bg.DailyBriefing)
  403. {
  404. services.AddHostedService<DailyBriefingPublisher>();
  405. }
  406. return services;
  407. }
  408. /**
  409. * ========================================================================================================================================================================================================
  410. * ========================================================================================================================================================================================================
  411. */
  412. // Admin 전용 — 백그라운드 서비스는 포함하지 않음 (Web.Api에서만 돌아야 함)
  413. // 메일은 즉시 SMTP 발송 (DirectMailService)
  414. public static IServiceCollection AddAdminInfrastructure(this IServiceCollection services, IConfiguration configuration)
  415. {
  416. services.AddScoped<IMailService, DirectMailService>();
  417. return services.AddDatabase(configuration).AddRedis(configuration).AddCommonServices(configuration).AddHealthChecks(configuration);
  418. }
  419. /**
  420. * ========================================================================================================================================================================================================
  421. * ========================================================================================================================================================================================================
  422. */
  423. // API 전용 — 공용 서비스 + 백그라운드 서비스 모두 포함
  424. // 메일은 EmailLog 큐에 적재 (QueuedMailService) — MailWorker가 별도로 폴링하여 SMTP 송신
  425. public static IServiceCollection AddApiInfrastructure(this IServiceCollection services, IConfiguration configuration)
  426. {
  427. services.AddScoped<IMailService, QueuedMailService>();
  428. return services.AddDatabase(configuration).AddRedis(configuration).AddApiAuthentication(configuration).AddCommonServices(configuration).AddBackgroundServices(configuration).AddPaymentBackgroundServices(configuration).AddStockDataServices(configuration).AddHealthChecks(configuration);
  429. }
  430. private static IServiceCollection AddApiAuthentication(this IServiceCollection services, IConfiguration configuration)
  431. {
  432. var settings = configuration.Get<AppSettings>()!;
  433. // 인증 정책- JWT Bearer
  434. services.AddAuthentication(options =>
  435. {
  436. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  437. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  438. })
  439. .AddJwtBearer(options =>
  440. {
  441. options.RequireHttpsMetadata = false;
  442. options.MapInboundClaims = false;
  443. options.TokenValidationParameters = new TokenValidationParameters
  444. {
  445. ValidateIssuer = true,
  446. ValidateAudience = true,
  447. ValidateLifetime = true,
  448. ValidateIssuerSigningKey = true,
  449. ValidIssuer = settings.JWT.Issuer,
  450. ValidAudience = settings.JWT.Audience,
  451. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.JWT.SecretKey)),
  452. ClockSkew = TimeSpan.Zero
  453. };
  454. options.Events = new JwtBearerEvents
  455. {
  456. OnMessageReceived = context =>
  457. {
  458. var accessToken = context.Request.Query["access_token"];
  459. var path = context.HttpContext.Request.Path;
  460. if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
  461. {
  462. context.Token = accessToken;
  463. }
  464. return Task.CompletedTask;
  465. }
  466. };
  467. });
  468. services.AddAuthorization();
  469. // Identity Core (Admin Handler의 UserManager/RoleManager 의존 해소용)
  470. services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
  471. return services;
  472. }
  473. }