using System.Globalization;
using Dpz.Core.Backup;
using Dpz.Core.MessageQueue.Extensions;
using Dpz.Core.Public.ViewModel.Messages;
using Dpz.Core.Service.Network;
using Dpz.Core.Service.RepositoryServiceImpl;
using Dpz.Core.Shard.Implement.Service;
using Dpz.Core.Shard.Service;
using Dpz.Core.WebApi.Service;
using Dpz.Core.WebApi.Services.Handlers;
using Hangfire;
using Microsoft.AspNetCore.Localization;

namespace Dpz.Core.WebApi;

/// <summary>
///
/// </summary>
public static class DependencyInjectionExtensions
{
    /// <param name="services"></param>
    extension(IServiceCollection services)
    {
        /// <summary>
        /// Ioc 注册
        /// </summary>
        /// <returns></returns>
        public IServiceCollection AddProjectServices()
        {
            services.AddHttpClient();

            services.AddHttpClient(
                "edge",
                httpClient =>
                {
                    httpClient.DefaultRequestHeaders.Add("User-Agent", EnvironmentInfo.UserAgent);
                }
            );

            // 添加 又拍云储存
            services.AddUpyunObjectStorage();
            // 视频处理
            services.AddVideoSyncHandleService();
            services.AddUpyunSafeFileService();
            services.AddBackupRestoreService();

            services.AddScoped<IVideoShardService, VideoShardService>();
            services.AddNetworkServices();
            services.AddHttpContextAccessor();
            services.AddScoped<ICurrentUserService, CurrentUserService>();

            services
                .AddHttpClient<ISteamGameService, SteamGameService>(
                    (_, client) =>
                    {
                        client.BaseAddress = new Uri("https://api.steampowered.com");
                    }
                )
                .ConfigurePrimaryHttpMessageHandler(_ => new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (_, _, _, _) => true,
                });
            return services;
        }

        /// <summary>
        /// 添加消息队列服务 注册消费者
        /// </summary>
        /// <param name="configuration"></param>
        public void AddMessageQueueServices(IConfiguration configuration)
        {
            services.AddBatchTracking();

            services.AddMessageConsumer<NewsArticleMessage, NewsArticleMessageHandler>();

            services.AddMessageConsumer<BatchCompletionMessage, BatchCompletionMessageHandler>();
        }
    }

    /// <summary>
    /// hangfire UI设置及周期性任务调度
    /// </summary>
    /// <param name="app"></param>
    /// <returns></returns>
    public static void HangfireSetting(this IApplicationBuilder app)
    {
        var supportedCultures = new[] { new CultureInfo("zh-CN") };
        app.UseRequestLocalization(
            new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("zh-CN"),
                // Formatting numbers, dates, etc.
                SupportedCultures = supportedCultures,
                // UI strings that we have localized.
                SupportedUICultures = supportedCultures,
            }
        );

        app.UseHangfireDashboard(
            "/jobs",
            new DashboardOptions
            {
                AppPath = "/",
                StatsPollingInterval = 5000,
                //可编辑任务
                IsReadOnlyFunc = _ => false,
                DarkModeEnabled = true,
                DashboardTitle = "任务管理",
                FaviconPath = "/favicon.ico",
            }
        );
    }
}
⚠⚠    以下内容为AI分析的结果,请根据实际情况进行判断。

这是一个ASP.NET Core项目中的依赖注入扩展类,主要用于配置和注册各种服务。让我详细解释一下这个代码:

类的整体结构

public static class DependencyInjectionExtensions

这是一个静态扩展类,用于扩展 IServiceCollectionIApplicationBuilder 的功能。

主要方法分析

1. AddProjectServices() 方法

这个方法负责注册项目中的核心服务:

HTTP客户端配置:

services.AddHttpClient(); // 注册默认HTTP客户端
services.AddHttpClient("edge", httpClient => {
    httpClient.DefaultRequestHeaders.Add("User-Agent", EnvironmentInfo.UserAgent);
}); // 注册名为"edge"的HTTP客户端,并设置User-Agent头

第三方服务注册:

services.AddUpyunObjectStorage();      // 又拍云存储服务
services.AddVideoSyncHandleService();  // 视频处理服务
services.AddUpyunSafeFileService();    // 又拍云安全文件服务
services.AddBackupRestoreService();    // 备份恢复服务

业务服务注册:

services.AddScoped<IVideoShardService, VideoShardService>(); // 视频分片服务
services.AddNetworkServices();                               // 网络服务
services.AddScoped<ICurrentUserService, CurrentUserService>(); // 当前用户服务

Steam API客户端配置:

services.AddHttpClient<ISteamGameService, SteamGameService>(
    (_, client) => {
        client.BaseAddress = new Uri("https://api.steampowered.com");
    })
    .ConfigurePrimaryHttpMessageHandler(_ => new HttpClientHandler {
        ServerCertificateCustomValidationCallback = (_, _, _, _) => true, // 忽略SSL证书验证
    });

2. AddMessageQueueServices() 方法

配置消息队列相关服务:

services.AddBatchTracking(); // 批处理跟踪服务

// 注册消息消费者
services.AddMessageConsumer<NewsArticleMessage, NewsArticleMessageHandler>();
services.AddMessageConsumer<BatchCompletionMessage, BatchCompletionMessageHandler>();

3. HangfireSetting() 方法

配置Hangfire任务调度系统:

本地化设置:

var supportedCultures = new[] { new CultureInfo("zh-CN") };
app.UseRequestLocalization(new RequestLocalizationOptions {
    DefaultRequestCulture = new RequestCulture("zh-CN"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures,
});

Hangfire Dashboard配置:

app.UseHangfireDashboard("/jobs", new DashboardOptions {
    AppPath = "/",
    StatsPollingInterval = 5000,    // 统计轮询间隔5秒
    IsReadOnlyFunc = _ => false,    // 允许编辑任务
    DarkModeEnabled = true,         // 启用暗色模式
    DashboardTitle = "任务管理",     // 仪表板标题
    FaviconPath = "/favicon.ico",   // 网站图标路径
});

代码问题

注意到代码中有一个语法错误:

extension(IServiceCollection services) // 这里应该是方法声明

应该修正为:

public static IServiceCollection AddProjectServices(this IServiceCollection services)

总结

这个扩展类的主要作用是:

  1. 服务注册:集中管理项目中各种服务的依赖注入配置
  2. HTTP客户端配置:为不同的外部API配置专用的HTTP客户端
  3. 消息队列:注册消息处理器和相关服务
  4. 任务调度:配置Hangfire的UI界面和本地化设置

这种设计模式有助于保持Program.csStartup.cs文件的简洁,同时将相关的服务注册逻辑组织在一起。

评论加载中...