DependencyInjection.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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.Persistence;
  16. using Infrastructure.Persistence.Identity;
  17. using Infrastructure.Storage;
  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.AddHttpClient<IUpbitClient, UpbitRestClient>(client =>
  81. {
  82. client.BaseAddress = new Uri("https://api.upbit.com/v1/");
  83. client.DefaultRequestHeaders.Add("Accept", "application/json");
  84. client.Timeout = TimeSpan.FromSeconds(10);
  85. });
  86. services.AddSingleton<IChatMessageStore, RedisChatMessageStore>();
  87. services.AddSingleton<IChatConnectionTracker, RedisChatConnectionTracker>();
  88. services.AddScoped<IBoardPermissionService, BoardPermissionService>();
  89. return services;
  90. }
  91. /**
  92. * ========================================================================================================================================================================================================
  93. * ========================================================================================================================================================================================================
  94. */
  95. // Admin 전용
  96. public static IServiceCollection AddAdminInfrastructure(this IServiceCollection services, IConfiguration configuration)
  97. {
  98. return services.AddDatabase(configuration).AddRedis(configuration).AddServices().AddHealthChecks(configuration);
  99. }
  100. /**
  101. * ========================================================================================================================================================================================================
  102. * ========================================================================================================================================================================================================
  103. */
  104. // API 전용
  105. public static IServiceCollection AddApiInfrastructure(this IServiceCollection services, IConfiguration configuration)
  106. {
  107. return services.AddDatabase(configuration).AddRedis(configuration).AddApiAuthentication(configuration).AddServices().AddUpbit().AddHealthChecks(configuration);
  108. }
  109. private static IServiceCollection AddUpbit(this IServiceCollection services)
  110. {
  111. services.AddHostedService<UpbitWebSocketService>();
  112. return services;
  113. }
  114. private static IServiceCollection AddApiAuthentication(this IServiceCollection services, IConfiguration configuration)
  115. {
  116. var settings = configuration.Get<AppSettings>()!;
  117. // 인증 정책- JWT Bearer
  118. services.AddAuthentication(options =>
  119. {
  120. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  121. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  122. })
  123. .AddJwtBearer(options =>
  124. {
  125. options.RequireHttpsMetadata = false;
  126. options.MapInboundClaims = false;
  127. options.TokenValidationParameters = new TokenValidationParameters
  128. {
  129. ValidateIssuer = true,
  130. ValidateAudience = true,
  131. ValidateLifetime = true,
  132. ValidateIssuerSigningKey = true,
  133. ValidIssuer = settings.JWT.Issuer,
  134. ValidAudience = settings.JWT.Audience,
  135. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.JWT.SecretKey)),
  136. ClockSkew = TimeSpan.Zero
  137. };
  138. options.Events = new JwtBearerEvents
  139. {
  140. OnMessageReceived = context =>
  141. {
  142. var accessToken = context.Request.Query["access_token"];
  143. var path = context.HttpContext.Request.Path;
  144. if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
  145. {
  146. context.Token = accessToken;
  147. }
  148. return Task.CompletedTask;
  149. }
  150. };
  151. });
  152. services.AddAuthorization();
  153. // Identity Core (Admin Handler의 UserManager/RoleManager 의존 해소용)
  154. services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
  155. return services;
  156. }
  157. }
  158. }