DependencyInjection.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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.AddTransient<IMailService, MailService>();
  74. services.AddTransient<IEmailSender, IdentityEmailSender>();
  75. services.AddScoped<IFileStorage, LocalFileStorage>();
  76. services.AddScoped<IEditorImageService, EditorImageService>();
  77. services.AddScoped<IIdentityUserReader, IdentityUserReader>();
  78. services.AddScoped<IIdentityUserWriter, IdentityUserWriter>();
  79. services.AddScoped<IIdentityRoleReader, IdentityRoleReader>();
  80. services.AddScoped<IIdentityRoleWriter, IdentityRoleWriter>();
  81. services.AddHttpClient<IUpbitClient, UpbitRestClient>(client =>
  82. {
  83. client.BaseAddress = new Uri("https://api.upbit.com/v1/");
  84. client.DefaultRequestHeaders.Add("Accept", "application/json");
  85. client.Timeout = TimeSpan.FromSeconds(10);
  86. });
  87. services.AddSingleton<IChatMessageStore, RedisChatMessageStore>();
  88. services.AddSingleton<IChatConnectionTracker, RedisChatConnectionTracker>();
  89. services.AddScoped<IBoardPermissionService, BoardPermissionService>();
  90. services.AddHttpClient<IGoogleTokenValidator, GoogleTokenValidator>();
  91. services.AddHttpClient("RssFeed", client =>
  92. {
  93. client.Timeout = TimeSpan.FromSeconds(30);
  94. client.DefaultRequestHeaders.Add("User-Agent", "BitForum/1.0");
  95. client.DefaultRequestHeaders.Add("Accept", "application/rss+xml, application/xml, text/xml");
  96. });
  97. return services;
  98. }
  99. /**
  100. * ========================================================================================================================================================================================================
  101. * ========================================================================================================================================================================================================
  102. */
  103. // Admin 전용
  104. public static IServiceCollection AddAdminInfrastructure(this IServiceCollection services, IConfiguration configuration)
  105. {
  106. return services.AddDatabase(configuration).AddRedis(configuration).AddServices().AddNews().AddHealthChecks(configuration);
  107. }
  108. /**
  109. * ========================================================================================================================================================================================================
  110. * ========================================================================================================================================================================================================
  111. */
  112. // API 전용
  113. public static IServiceCollection AddApiInfrastructure(this IServiceCollection services, IConfiguration configuration)
  114. {
  115. return services.AddDatabase(configuration).AddRedis(configuration).AddApiAuthentication(configuration).AddServices().AddUpbit().AddNews().AddHealthChecks(configuration);
  116. }
  117. private static IServiceCollection AddUpbit(this IServiceCollection services)
  118. {
  119. services.AddHostedService<UpbitWebSocketService>();
  120. return services;
  121. }
  122. private static IServiceCollection AddNews(this IServiceCollection services)
  123. {
  124. services.AddSingleton<RssCollectorService>();
  125. services.AddHostedService(sp => sp.GetRequiredService<RssCollectorService>());
  126. services.AddSingleton<Application.Abstractions.News.IRssCollector>(sp => sp.GetRequiredService<RssCollectorService>());
  127. return services;
  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. }