| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508 |
- using Application.Abstractions.Authentication;
- using Application.Abstractions.Cache;
- using Application.Abstractions.Chat;
- using Application.Abstractions.Crypto;
- using Application.Abstractions.Data;
- using Application.Abstractions.Hub;
- using Application.Abstractions.Identity;
- using Application.Abstractions.Forum;
- using Application.Abstractions.Messaging.Email;
- using Application.Abstractions.Notification;
- using Application.Abstractions.Payment;
- using Application.Abstractions.YouTube;
- using Application.Helpers;
- using Infrastructure.Authentication;
- using Infrastructure.Crypto;
- using Infrastructure.Payment;
- using Infrastructure.Forum;
- using Infrastructure.Cache;
- using Infrastructure.Chat;
- using Infrastructure.Messaging.Email;
- using Infrastructure.Persistence;
- using Infrastructure.Persistence.Identity;
- using Infrastructure.StockData;
- using Infrastructure.Storage;
- using Infrastructure.YouTube;
- using Microsoft.AspNetCore.Authentication;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- using Microsoft.AspNetCore.DataProtection;
- using Microsoft.AspNetCore.Identity;
- using Microsoft.AspNetCore.Identity.UI.Services;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.EntityFrameworkCore.Diagnostics;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Options;
- using Microsoft.IdentityModel.Tokens;
- using SharedKernel;
- using SharedKernel.Storage;
- using StackExchange.Redis;
- using System.Text;
- namespace Infrastructure;
- public static class DependencyInjection
- {
- // SQL Server
- private static IServiceCollection AddDatabase(this IServiceCollection services, IConfiguration configuration)
- {
- var dbConn = configuration.GetConnectionString("DefaultConnection");
- if (string.IsNullOrWhiteSpace(dbConn))
- {
- throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured.");
- }
- // Pooling: 매 request 마다 새 DbContext 생성 비용 제거. ChangeTracker 등 내부 상태는 풀 반환 시 자동 reset
- // ConfigureWarnings: EF 9+의 PendingModelChangesWarning을 무시 (snapshot 일관성 문제로 false-positive 발생, 마이그레이션은 별도 관리)
- void ConfigureAppDb(DbContextOptionsBuilder options) => options
- .UseSqlServer(dbConn)
- .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning));
- services.AddDbContextPool<AppDbContext>(ConfigureAppDb, poolSize: 128);
- services.AddDbContextPool<IdentityDbContext>(options => options
- .UseSqlServer(dbConn)
- .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning)), poolSize: 64);
- services.AddScoped<IAppDbContext>(sp => sp.GetRequiredService<AppDbContext>());
- // Phase 1.5: out-of-band 커밋(대사 로그·동시성 재시도)용 풀링 팩토리.
- // 내부 등록이 전부 TryAdd 라 위 AddDbContextPool 과 같은 옵션·풀을 공유하며 중복 등록 없이 공존한다.
- services.AddPooledDbContextFactory<AppDbContext>(ConfigureAppDb, poolSize: 128);
- services.AddSingleton<IAppDbContextFactory, AppDbContextFactory>();
- return services;
- }
- // Redis Server
- public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
- {
- var settings = configuration.Get<AppSettings>()!;
- var redis = ConnectionMultiplexer.Connect(settings.Redis.DefaultConnection);
- services.AddSingleton<IConnectionMultiplexer>(redis);
- services.AddDataProtection()
- .SetApplicationName(settings.App.Name)
- .PersistKeysToStackExchangeRedis(redis, settings.Redis.DataProtectionKey)
- .ProtectKeysWithDpapi(protectToLocalMachine: true) // key를 암호화하여 저장 (로컬 머신에서만 복호화 가능, 서버간 공유 불가)
- .SetDefaultKeyLifetime(settings.Redis.DefaultKeyLifetime); // 기본 90일 주기
- // Distributed Cache 설정
- services.AddStackExchangeRedisCache(options =>
- {
- options.Configuration = settings.Redis.DefaultConnection;
- options.InstanceName = settings.Redis.CachePrefix;
- });
- return services;
- }
- private static IServiceCollection AddHealthChecks(this IServiceCollection services, IConfiguration configuration)
- {
- var settings = configuration.Get<AppSettings>()!;
- services.AddHealthChecks().AddSqlServer(settings.ConnectionStrings.DefaultConnection).AddRedis(settings.Redis.DefaultConnection);
- return services;
- }
- // Admin/Api 둘 다 필요한 공용 서비스 (singleton/transient/scoped, HttpClient)
- private static IServiceCollection AddCommonServices(this IServiceCollection services, IConfiguration configuration)
- {
- // 파일 저장 위치 옵션 (deploy 영향 받지 않는 외부 경로 권장)
- services.Configure<StorageOptions>(configuration.GetSection(StorageOptions.SectionName));
- services.AddSingleton<IJwtTokenProvider, JwtTokenProvider>();
- services.AddSingleton<ILegacyPasswordVerifier, BcryptLegacyPasswordVerifier>();
- services.AddSingleton<ICacheService, RedisCacheService>();
- services.AddSingleton<IFieldEncryptor, AesGcmFieldEncryptor>();
- services.AddTransient<IEmailSender, IdentityEmailSender>();
- services.AddScoped<IFileStorage, LocalFileStorage>();
- services.AddScoped<IEditorImageService, EditorImageService>();
- services.AddScoped<IIdentityUserReader, IdentityUserReader>();
- services.AddScoped<IIdentityUserWriter, IdentityUserWriter>();
- services.AddScoped<IIdentityRoleReader, IdentityRoleReader>();
- services.AddScoped<IIdentityRoleWriter, IdentityRoleWriter>();
- services.AddSingleton<IChatMessageStore, RedisChatMessageStore>();
- services.AddSingleton<IChatConnectionTracker, RedisChatConnectionTracker>();
- services.AddSingleton<IChatLeaderboard, RedisChatLeaderboard>();
- services.AddSingleton<Application.Abstractions.Paper.IPaperLeaderboardCache, Paper.PaperLeaderboardCache>();
- services.AddSingleton<Application.Abstractions.Stocks.IStockBoardTrendingCache, Stocks.RedisStockBoardTrendingCache>();
- services.AddSingleton<IChatRewardHook, RewardChatHook>(); // D3 M2 실구현 — ChatExpConfig 수치를 RewardService 로 지급 (d0 §2.2)
- services.AddSingleton<IPresenceTracker, Hubs.PresenceTracker>();
- services.AddSingleton<IVisitorTracker, Hubs.RedisVisitorTracker>();
- services.AddScoped<IBoardPermissionService, BoardPermissionService>();
- services.AddHttpClient<IGoogleTokenValidator, GoogleTokenValidator>();
- // 소셜 로그인 provider (개미투자 D5 — Naver/Kakao authorization code). 핸들러가 IEnumerable 에서 이름으로 해석
- services.AddHttpClient<NaverAuthProvider>();
- services.AddHttpClient<KakaoAuthProvider>();
- services.AddTransient<ISocialAuthProvider>(sp => sp.GetRequiredService<NaverAuthProvider>());
- services.AddTransient<ISocialAuthProvider>(sp => sp.GetRequiredService<KakaoAuthProvider>());
- // YouTube & Google OAuth (HttpClients + singletons — Admin에서도 "API 키 테스트" 등에 쓰므로 공용)
- services.AddSingleton<IYouTubeApiKeyProvider, YouTubeApiKeyProvider>();
- services.AddTransient<YouTubeApiKeyHandler>();
- services.AddTransient<IYouTubeApiConnectionTester, YouTubeApiConnectionTester>();
- services.AddHttpClient("YouTubeApi", client =>
- {
- client.Timeout = TimeSpan.FromSeconds(15);
- client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
- })
- .AddHttpMessageHandler<YouTubeApiKeyHandler>();
- services.AddHttpClient("PubSubHub", client =>
- {
- client.Timeout = TimeSpan.FromSeconds(15);
- });
- services.AddHttpClient("YouTubeFeed", client =>
- {
- client.Timeout = TimeSpan.FromSeconds(10);
- client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/atom+xml"));
- });
- services.AddHttpClient<IGoogleOAuthService, GoogleOAuthService>();
- services.AddHttpClient<ITossPaymentService, TossPaymentService>(client =>
- {
- client.Timeout = TimeSpan.FromSeconds(60); // 토스 승인 API 권장 타임아웃 — 짧으면 통신 불명(대사 대상)만 늘어난다
- });
- services.AddSingleton<IYouTubeApiService, YouTubeApiService>();
- services.AddSingleton<IYouTubeChannelCache, YouTubeChannelCache>();
- services.AddSingleton<IYouTubeLiveStateStore, YouTubeLiveStateStore>();
- services.AddSingleton<YouTubeLiveChatService>();
- services.AddSingleton<IYouTubeLiveChatService>(sp => sp.GetRequiredService<YouTubeLiveChatService>());
- services.AddSingleton<YouTubePubSubService>();
- services.AddSingleton<IYouTubePubSubService>(sp => sp.GetRequiredService<YouTubePubSubService>());
- services.AddSingleton<IYouTubeFeedPoller, YouTubeFeedPoller>();
- // Notification
- services.AddScoped<INotificationService, Notification.NotificationService>();
- // Feed broadcaster (SignalR)
- services.AddScoped<IFeedBroadcaster, Hubs.FeedBroadcaster>();
- // Channel status broadcaster (라이브 시작/종료/시청자 수 → AppHub 브로드캐스트)
- services.AddSingleton<IChannelStatusBroadcaster, Hubs.ChannelStatusBroadcaster>();
- return services;
- }
- // Web.Api 전용 백그라운드 서비스 (Admin에서 중복 실행되면 quota 2배/폴링 2번 문제)
- // appsettings.json BackgroundJobs 섹션으로 개별 토글 (기본 모두 true). 진단용 A/B 테스트에 사용
- private static IServiceCollection AddBackgroundServices(this IServiceCollection services, IConfiguration configuration)
- {
- // Features:Channel OFF → YouTube/채널 백그라운드 서비스 전체 미등록 (코드 보존, 기능 노출 0)
- var features = configuration.GetSection("Features").Get<AppSettings.FeaturesSection>() ?? new AppSettings.FeaturesSection();
- if (!features.Channel)
- {
- return services;
- }
- var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
- if (bg.LiveChat)
- {
- services.AddHostedService(sp => sp.GetRequiredService<YouTubeLiveChatService>());
- }
- if (bg.PubSubRenewal)
- {
- services.AddHostedService<YouTubePubSubRenewalService>();
- }
- if (bg.FeedPolling)
- {
- services.AddHostedService<YouTubeFeedPollingService>();
- }
- if (bg.LiveViewerPoller)
- {
- services.AddHostedService<YouTubeLiveViewerPoller>();
- }
- if (bg.ChannelCacheRefresh)
- {
- services.AddHostedService<YouTubeChannelCacheRefreshService>();
- }
- if (bg.YouTubeDailyAggregator)
- {
- services.AddHostedService<YouTubeDailyAggregatorService>();
- }
- if (bg.YouTubeStaleDataPurge)
- {
- services.AddHostedService<YouTubeStaleDataPurgeService>();
- }
- return services;
- }
- // 결제 자동 대사 배치 (Toss NeedsReconciliation 재확인) — Features:Channel 게이트 밖 별도 등록, Web.Api 전용.
- // BackgroundJobs:PaymentReconcile 플래그로 토글 (기본 true — 대상 없으면 PG 호출 없이 skip)
- private static IServiceCollection AddPaymentBackgroundServices(this IServiceCollection services, IConfiguration configuration)
- {
- var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
- if (bg.PaymentReconcile)
- {
- services.AddHostedService<PaymentReconcileService>();
- }
- return services;
- }
- // 주식 데이터 수집 배치 (개미투자 D1) — Features:Channel 게이트 밖 별도 등록.
- // StockData 섹션 플래그로 개별 토글 (기본 모두 false — API 키 발급/운영 결정 후 활성화)
- private static IServiceCollection AddStockDataServices(this IServiceCollection services, IConfiguration configuration)
- {
- services.AddHttpClient(DataGoKrHttp.ClientName, client =>
- {
- client.Timeout = TimeSpan.FromSeconds(30);
- client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
- });
- // KRX OpenAPI(data-dbg.krx.co.kr) 지수 수집 클라이언트 — AUTH_KEY 헤더는 요청 단위로 부여 (KrxCoKrHttp)
- services.AddHttpClient(KrxCoKrHttp.ClientName, client =>
- {
- client.Timeout = TimeSpan.FromSeconds(30);
- client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
- });
- // OpenDART(opendart.fss.or.kr) 공시 수집 클라이언트 — 인증은 URL query param crtfc_key (요청 단위, OpenDartHttp)
- services.AddHttpClient(OpenDartHttp.ClientName, client =>
- {
- client.Timeout = TimeSpan.FromSeconds(30);
- client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
- });
- // 한국수출입은행(koreaexim.go.kr) 거시·환율 수집 클라이언트 — 인증은 URL query param authkey (요청 단위, KoreaEximHttp)
- services.AddHttpClient(KoreaEximHttp.ClientName, client =>
- {
- client.Timeout = TimeSpan.FromSeconds(30);
- client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
- });
- // SEIBro OpenAPI(seibro.or.kr) 수집 클라이언트 — 인증은 URL query param key (요청 단위, SeibroHttp). 응답은 XML
- services.AddHttpClient(SeibroHttp.ClientName, client =>
- {
- client.Timeout = TimeSpan.FromSeconds(30);
- client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
- });
- // SEIBro 카테고리별 일일 호출 예산 트래커 — 같은 카테고리 배치들이 하나의 카운터를 공유 (in-memory, KST 자정 롤오버)
- services.AddSingleton(_ => new SeibroQuota());
- var stockData = configuration.GetSection("StockData").Get<AppSettings.StockDataSection>() ?? new AppSettings.StockDataSection();
- if (stockData.MasterSync)
- {
- services.AddHostedService<StockMasterSyncService>();
- }
- if (stockData.DailyPriceSync)
- {
- services.AddHostedService<DailyPriceSyncService>();
- }
- // 지수(시장) 일별시세 수집 (KRX OpenAPI) — KRXCoKr:IndexSync 플래그 (기본 false). KOSPI/KOSDAQ/KRX + 파생상품지수 한 배치
- var krx = configuration.GetSection("KRXCoKr").Get<AppSettings.KRXCoKrSection>() ?? new AppSettings.KRXCoKrSection();
- if (krx.IndexSync)
- {
- services.AddHostedService<IndexPriceSyncService>();
- }
- // 채권지수 일별시세 수집 (KRX OpenAPI idx/bon_dd_trd) — KRXCoKr:BondIndexSync 플래그 (기본 false). 응답 shape 이 달라 별도 배치. KRXCoKr HttpClient 재사용
- if (krx.BondIndexSync)
- {
- services.AddHostedService<BondIndexPriceSyncService>();
- }
- // 주식(종목) 마스터 + 일별매매 수집 (KRX OpenAPI) — KRXCoKr:StockSync 플래그 (기본 false). KRXCoKr HttpClient 재사용
- if (krx.StockSync)
- {
- services.AddHostedService<KrxStockMasterSyncService>();
- services.AddHostedService<KrxDailyPriceSyncService>();
- }
- // 증권상품(ETF/ETN/ELW) 일별매매 수집 (KRX OpenAPI) — KRXCoKr:EtpSync 플래그 (기본 false). KRXCoKr HttpClient 재사용
- if (krx.EtpSync)
- {
- services.AddHostedService<KrxEtpSyncService>();
- }
- // 신주인수권증권/증서 일별매매 수집 (KRX OpenAPI) — KRXCoKr:WarrantSync 플래그 (기본 false). KRXCoKr HttpClient 재사용
- if (krx.WarrantSync)
- {
- services.AddHostedService<KrxWarrantSyncService>();
- }
- // 채권(국채전문유통/일반채권/소액채권) 일별매매 수집 (KRX OpenAPI) — KRXCoKr:BondSync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
- if (krx.BondSync)
- {
- services.AddHostedService<KrxBondSyncService>();
- }
- // 파생상품(선물 3 + 옵션 3) 일별매매 수집 (KRX OpenAPI drv) — KRXCoKr:DerivativeSync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
- if (krx.DerivativeSync)
- {
- services.AddHostedService<KrxDerivativeSyncService>();
- }
- // 일반상품(석유·금·배출권) 일별매매 수집 (KRX OpenAPI gen) — KRXCoKr:CommoditySync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
- if (krx.CommoditySync)
- {
- services.AddHostedService<KrxCommoditySyncService>();
- }
- // ESG 데이터(ESG 증권상품 + ESG 지수 + 사회책임투자채권) 수집 (KRX OpenAPI esg) — KRXCoKr:EsgSync 플래그 (기본 false). KrxBackfill 로 최근 3년 백필. KRXCoKr HttpClient 재사용
- if (krx.EsgSync)
- {
- services.AddHostedService<KrxEsgSyncService>();
- }
- // 전자공시(DART) 공시 목록 수집 (OpenDART list.json) — OpenDart:DisclosureSync 플래그 (기본 false). 접수일 최근 N일 페이징. OpenDart HttpClient 사용
- var dart = configuration.GetSection("OpenDart").Get<AppSettings.OpenDartSection>() ?? new AppSettings.OpenDartSection();
- if (dart.DisclosureSync)
- {
- services.AddHostedService<DisclosureSyncService>();
- }
- // 거시·환율 수집 (한국수출입은행 AP01 환율 + AP02 대출금리 + AP03 국제금리) — KoreaExim:MacroSync 플래그 (기본 false). KrxBackfill 로 최근 N일 백필. KoreaExim HttpClient 사용
- var koreaExim = configuration.GetSection("KoreaExim").Get<AppSettings.KoreaEximSection>() ?? new AppSettings.KoreaEximSection();
- if (koreaExim.MacroSync)
- {
- services.AddHostedService<MacroDataSyncService>();
- }
- // SEIBro 발행회사번호(조인키) 부트스트랩 + 종목 보강 (getShotnByMart/getStkStatInfo) — Seibro:IssuerSync 플래그 (기본 false). Seibro HttpClient + SeibroQuota 사용
- var seibro = configuration.GetSection("Seibro").Get<AppSettings.SeibroSection>() ?? new AppSettings.SeibroSection();
- if (seibro.IssuerSync)
- {
- services.AddHostedService<SeibroIssuerSyncService>();
- }
- // SEIBro 배당·권리 수집 (getDivSchedulInfo/getDivInfo/getStddtInfo) — Seibro:DividendSync 플래그 (기본 false). Corp 카테고리 예산 공유
- if (seibro.DividendSync)
- {
- services.AddHostedService<SeibroDividendSyncService>();
- }
- // SEIBro 수급 이벤트 수집 (대차·보호예수·증감·유통변경·비상장) — Seibro:SupplySync 플래그 (기본 false). Stock 카테고리 예산 공유
- if (seibro.SupplySync)
- {
- services.AddHostedService<SeibroSupplySyncService>();
- }
- // SEIBro 기업행위·총회 수집 (총회·상호변경·대금·단주·CB/BW 행사) — Seibro:CorpActionSync 플래그 (기본 false). 총회·상호·대금·단주=Corp 예산, CB/BW 행사=Stock 예산 공유
- if (seibro.CorpActionSync)
- {
- services.AddHostedService<SeibroCorpActionSyncService>();
- }
- // SEIBro 채권·단기금융 수집 (발행·마스터·이자·조기상환·단기발행·CD/CP/전단채) — Seibro:BondSync 플래그 (기본 false). Bond 카테고리 예산 공유
- if (seibro.BondSync)
- {
- services.AddHostedService<SeibroBondSyncService>();
- }
- // SEIBro 파생결합증권 ELS/DLS 수집 (발행·마스터·기초자산·행사·상환조건·상환종목·미상환규모) — Seibro:DerivSync 플래그 (기본 false). Deriv 카테고리 예산 공유
- if (seibro.DerivSync)
- {
- services.AddHostedService<SeibroDerivSyncService>();
- }
- // 모의투자 체결·스냅샷 배치 (d4 M2) — BackgroundJobs:PaperFill 플래그 (기본 false). Web.Api 전용.
- var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
- if (bg.PaperFill)
- {
- services.AddHostedService<PaperFillService>();
- }
- // 예측 채점 배치 (d2 M4) — BackgroundJobs:PredictionSettlement 플래그 (기본 false). Web.Api 전용.
- if (bg.PredictionSettlement)
- {
- services.AddHostedService<PredictionSettlementService>();
- }
- // 장전 브리핑 자동 발행 배치 (d2 M3) — BackgroundJobs:DailyBriefing 플래그 (기본 false, 07:30 KST). Web.Api 전용.
- if (bg.DailyBriefing)
- {
- services.AddHostedService<DailyBriefingPublisher>();
- }
- return services;
- }
- /**
- * ========================================================================================================================================================================================================
- * ========================================================================================================================================================================================================
- */
- // Admin 전용 — 백그라운드 서비스는 포함하지 않음 (Web.Api에서만 돌아야 함)
- // 메일은 즉시 SMTP 발송 (DirectMailService)
- public static IServiceCollection AddAdminInfrastructure(this IServiceCollection services, IConfiguration configuration)
- {
- services.AddScoped<IMailService, DirectMailService>();
- return services.AddDatabase(configuration).AddRedis(configuration).AddCommonServices(configuration).AddHealthChecks(configuration);
- }
- /**
- * ========================================================================================================================================================================================================
- * ========================================================================================================================================================================================================
- */
- // API 전용 — 공용 서비스 + 백그라운드 서비스 모두 포함
- // 메일은 EmailLog 큐에 적재 (QueuedMailService) — MailWorker가 별도로 폴링하여 SMTP 송신
- public static IServiceCollection AddApiInfrastructure(this IServiceCollection services, IConfiguration configuration)
- {
- services.AddScoped<IMailService, QueuedMailService>();
- return services.AddDatabase(configuration).AddRedis(configuration).AddApiAuthentication(configuration).AddCommonServices(configuration).AddBackgroundServices(configuration).AddPaymentBackgroundServices(configuration).AddStockDataServices(configuration).AddHealthChecks(configuration);
- }
- private static IServiceCollection AddApiAuthentication(this IServiceCollection services, IConfiguration configuration)
- {
- var settings = configuration.Get<AppSettings>()!;
- // 인증 정책- JWT Bearer
- services.AddAuthentication(options =>
- {
- options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
- options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
- })
- .AddJwtBearer(options =>
- {
- options.RequireHttpsMetadata = false;
- options.MapInboundClaims = false;
- options.TokenValidationParameters = new TokenValidationParameters
- {
- ValidateIssuer = true,
- ValidateAudience = true,
- ValidateLifetime = true,
- ValidateIssuerSigningKey = true,
- ValidIssuer = settings.JWT.Issuer,
- ValidAudience = settings.JWT.Audience,
- IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.JWT.SecretKey)),
- ClockSkew = TimeSpan.Zero
- };
- options.Events = new JwtBearerEvents
- {
- OnMessageReceived = context =>
- {
- var accessToken = context.Request.Query["access_token"];
- var path = context.HttpContext.Request.Path;
- if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
- {
- context.Token = accessToken;
- }
- return Task.CompletedTask;
- }
- };
- });
- services.AddAuthorization();
- // Identity Core (Admin Handler의 UserManager/RoleManager 의존 해소용)
- services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
- return services;
- }
- }
|