DependencyInjection.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. using Application.Abstractions.Authentication;
  2. using Application.Abstractions.Cache;
  3. using Application.Abstractions.Chat;
  4. using Application.Abstractions.Data;
  5. using Application.Abstractions.Identity;
  6. using Application.Abstractions.Forum;
  7. using Application.Abstractions.Messaging.Email;
  8. using Application.Abstractions.Notification;
  9. using Application.Abstractions.Payment;
  10. using Application.Abstractions.YouTube;
  11. using Infrastructure.Authentication;
  12. using Infrastructure.Payment;
  13. using Infrastructure.Forum;
  14. using Infrastructure.Cache;
  15. using Infrastructure.Chat;
  16. using Infrastructure.Messaging.Email;
  17. using Infrastructure.Persistence;
  18. using Infrastructure.Persistence.Identity;
  19. using Infrastructure.Storage;
  20. using Infrastructure.YouTube;
  21. using Microsoft.AspNetCore.Authentication.JwtBearer;
  22. using Microsoft.AspNetCore.DataProtection;
  23. using Microsoft.AspNetCore.Identity;
  24. using Microsoft.AspNetCore.Identity.UI.Services;
  25. using Microsoft.EntityFrameworkCore;
  26. using Microsoft.Extensions.Configuration;
  27. using Microsoft.Extensions.DependencyInjection;
  28. using Microsoft.IdentityModel.Tokens;
  29. using SharedKernel;
  30. using SharedKernel.Storage;
  31. using StackExchange.Redis;
  32. using System.Text;
  33. namespace Infrastructure
  34. {
  35. public static class DependencyInjection
  36. {
  37. // SQL Server
  38. private static IServiceCollection AddDatabase(this IServiceCollection services, IConfiguration configuration)
  39. {
  40. var dbConn = configuration.GetConnectionString("DefaultConnection");
  41. if (string.IsNullOrWhiteSpace(dbConn))
  42. {
  43. throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured.");
  44. }
  45. services.AddDbContext<AppDbContext>(options => options.UseSqlServer(dbConn));
  46. services.AddDbContext<IdentityDbContext>(options => options.UseSqlServer(dbConn));
  47. services.AddScoped<IAppDbContext>(sp => sp.GetRequiredService<AppDbContext>());
  48. return services;
  49. }
  50. // Redis Server
  51. public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
  52. {
  53. var settings = configuration.Get<AppSettings>()!;
  54. var redis = ConnectionMultiplexer.Connect(settings.Redis.DefaultConnection);
  55. services.AddSingleton<IConnectionMultiplexer>(redis);
  56. services.AddDataProtection().SetApplicationName(settings.App.Name).PersistKeysToStackExchangeRedis(redis, settings.Redis.DataProtectionKey).SetDefaultKeyLifetime(settings.Redis.DefaultKeyLifetime); // 기본 90일 주기
  57. // Distributed Cache 설정
  58. services.AddStackExchangeRedisCache(options =>
  59. {
  60. options.Configuration = settings.Redis.DefaultConnection;
  61. options.InstanceName = settings.Redis.CachePrefix;
  62. });
  63. return services;
  64. }
  65. private static IServiceCollection AddHealthChecks(this IServiceCollection services, IConfiguration configuration)
  66. {
  67. var settings = configuration.Get<AppSettings>()!;
  68. services.AddHealthChecks().AddSqlServer(settings.ConnectionStrings.DefaultConnection).AddRedis(settings.Redis.DefaultConnection);
  69. return services;
  70. }
  71. private static IServiceCollection AddServices(this IServiceCollection services)
  72. {
  73. services.AddSingleton<IJwtTokenProvider, JwtTokenProvider>();
  74. services.AddSingleton<ICacheService, RedisCacheService>();
  75. services.AddTransient<IMailService, MailService>();
  76. services.AddTransient<IEmailSender, IdentityEmailSender>();
  77. services.AddScoped<IFileStorage, LocalFileStorage>();
  78. services.AddScoped<IEditorImageService, EditorImageService>();
  79. services.AddScoped<IIdentityUserReader, IdentityUserReader>();
  80. services.AddScoped<IIdentityUserWriter, IdentityUserWriter>();
  81. services.AddScoped<IIdentityRoleReader, IdentityRoleReader>();
  82. services.AddScoped<IIdentityRoleWriter, IdentityRoleWriter>();
  83. services.AddSingleton<IChatMessageStore, RedisChatMessageStore>();
  84. services.AddSingleton<IChatConnectionTracker, RedisChatConnectionTracker>();
  85. services.AddScoped<IBoardPermissionService, BoardPermissionService>();
  86. services.AddHttpClient<IGoogleTokenValidator, GoogleTokenValidator>();
  87. // YouTube & Google OAuth
  88. services.AddTransient<YouTubeApiKeyHandler>();
  89. services.AddHttpClient("YouTubeApi", client =>
  90. {
  91. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  92. })
  93. .AddHttpMessageHandler<YouTubeApiKeyHandler>();
  94. services.AddHttpClient("PubSubHub");
  95. services.AddHttpClient<IGoogleOAuthService, GoogleOAuthService>();
  96. services.AddHttpClient<IDanalPayService, DanalPayService>();
  97. services.AddSingleton<IYouTubeApiService, YouTubeApiService>();
  98. services.AddSingleton<IYouTubeChannelCache, YouTubeChannelCache>();
  99. services.AddSingleton<IYouTubeLiveStateStore, YouTubeLiveStateStore>();
  100. services.AddSingleton<YouTubeLiveChatService>();
  101. services.AddSingleton<IYouTubeLiveChatService>(sp => sp.GetRequiredService<YouTubeLiveChatService>());
  102. services.AddHostedService(sp => sp.GetRequiredService<YouTubeLiveChatService>());
  103. services.AddSingleton<YouTubePubSubService>();
  104. services.AddSingleton<IYouTubePubSubService>(sp => sp.GetRequiredService<YouTubePubSubService>());
  105. services.AddHostedService<YouTubePubSubRenewalService>();
  106. services.AddHostedService<YouTubeChannelCacheRefreshService>();
  107. // Notification
  108. services.AddScoped<INotificationService, Notification.NotificationService>();
  109. return services;
  110. }
  111. /**
  112. * ========================================================================================================================================================================================================
  113. * ========================================================================================================================================================================================================
  114. */
  115. // Admin 전용
  116. public static IServiceCollection AddAdminInfrastructure(this IServiceCollection services, IConfiguration configuration)
  117. {
  118. return services.AddDatabase(configuration).AddRedis(configuration).AddServices().AddHealthChecks(configuration);
  119. }
  120. /**
  121. * ========================================================================================================================================================================================================
  122. * ========================================================================================================================================================================================================
  123. */
  124. // API 전용
  125. public static IServiceCollection AddApiInfrastructure(this IServiceCollection services, IConfiguration configuration)
  126. {
  127. return services.AddDatabase(configuration).AddRedis(configuration).AddApiAuthentication(configuration).AddServices().AddHealthChecks(configuration);
  128. }
  129. private static IServiceCollection AddApiAuthentication(this IServiceCollection services, IConfiguration configuration)
  130. {
  131. var settings = configuration.Get<AppSettings>()!;
  132. // 인증 정책- JWT Bearer
  133. services.AddAuthentication(options =>
  134. {
  135. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  136. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  137. })
  138. .AddJwtBearer(options =>
  139. {
  140. options.RequireHttpsMetadata = false;
  141. options.MapInboundClaims = false;
  142. options.TokenValidationParameters = new TokenValidationParameters
  143. {
  144. ValidateIssuer = true,
  145. ValidateAudience = true,
  146. ValidateLifetime = true,
  147. ValidateIssuerSigningKey = true,
  148. ValidIssuer = settings.JWT.Issuer,
  149. ValidAudience = settings.JWT.Audience,
  150. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.JWT.SecretKey)),
  151. ClockSkew = TimeSpan.Zero
  152. };
  153. options.Events = new JwtBearerEvents
  154. {
  155. OnMessageReceived = context =>
  156. {
  157. var accessToken = context.Request.Query["access_token"];
  158. var path = context.HttpContext.Request.Path;
  159. if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
  160. {
  161. context.Token = accessToken;
  162. }
  163. return Task.CompletedTask;
  164. }
  165. };
  166. });
  167. services.AddAuthorization();
  168. // Identity Core (Admin Handler의 UserManager/RoleManager 의존 해소용)
  169. services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
  170. return services;
  171. }
  172. }
  173. }