DependencyInjection.cs 8.1 KB

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