DependencyInjection.cs 9.2 KB

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