DependencyInjection.cs 9.0 KB

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