网站首页 网站源码
website
站点相关全部源代码,隐藏了一些关于服务器的信息
using System.Net.Http;
using Microsoft.Extensions.Logging;
using Moq;

namespace Dpz.Core.ServiceTest;

public abstract class Basic
{
    private readonly IServiceProvider _serviceProvider;

    protected Basic()
    {
        var config = new ConfigurationBuilder()
            .AddJsonFile("appsettings.Test.json")
            .Build();
        Configuration = config;
        ConnectionString = Configuration.GetConnectionString("mongodb");
        IServiceCollection services = new ServiceCollection();

        // const string cacheName = "redis";
        // const string memoryCacheName = "dpangzi-memory";
        // services.AddEasyCaching(options =>
        // {
        //     options.UseInMemory(memoryCacheName);
        //     options.UseHybrid(cacheConfig =>
        //     {
        //         cacheConfig.TopicName = "service-cache";
        //         cacheConfig.EnableLogging = true;
        //         cacheConfig.LocalCacheProviderName = memoryCacheName;
        //         cacheConfig.DistributedCacheProviderName = cacheName;
        //     }, "hybrid-cache");
        // });
        services.AddBusinessServices(Configuration);


        services.AddSingleton<IConfiguration>(_ => config);
        services.AddSingleton<HttpClient>(_ => new HttpClient());
        services.AddSingleton<IMapper>(_ => ServiceMapper.Instance.Mapper);
        services.AddTransient<IUnitOfWork, UnitOfWork>();
        services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
        services.AddScoped<IWaitExecutionService, WaitExecutionService>();
        services.AddScoped<IObjectStorageOperation, ObjectStorageService>();
        services.AddScoped<IAccountService, AccountService>();
        services.AddScoped<IMaterialIconService, MaterialIconService>();
        services.AddScoped<IAppOptionService, AppOptionService>();
        
        
        //Steam API
        services.AddHttpClient<ISteamGameService, SteamGameService>((sp, client) =>
        {
            ActivatorUtilities.CreateInstance<SteamGameService>(sp);
            client.BaseAddress = new Uri("https://api.steampowered.com");
        }).ConfigurePrimaryHttpMessageHandler(_ => new HttpClientHandler
        {
            ServerCertificateCustomValidationCallback = (_, _, _, _) => true
        });

        _serviceProvider = services
            .AddLogging(builder => builder.AddConsole())
            .BuildServiceProvider();
    }

    protected T GetService<T>()
    {
        return _serviceProvider.GetService<T>() ?? throw new Exception($"service {typeof(T).Name} is null");
    }

    protected IServiceProvider ServiceProvider => _serviceProvider;

    protected string? ConnectionString { get; }

    protected IConfiguration Configuration { get; }

    // protected IEasyCachingProvider CachingProvider => _serviceProvider.GetService<IEasyCachingProvider>();
    //
    // protected IHybridCachingProvider HybridCachingProvider => _serviceProvider.GetService<IHybridCachingProvider>();

    protected IMapper Mapper => ServiceMapper.Instance.Mapper;

    protected IRepository<AppOption> AppOptionRepository => new Repository<AppOption>(ConnectionString);

    protected IRepository<Comment> CommentRepository => new Repository<Comment>(ConnectionString);

    protected IRepository<Article> ArticleRepository => new Repository<Article>(ConnectionString);

    protected IRepository<Mumble> MumbleRepository => new Repository<Mumble>(ConnectionString);

    protected IRepository<PageMetadata> PageMetadataRepository => new Repository<PageMetadata>(ConnectionString);

    protected IRepository<SteamGame> SteamGameRepository => new Repository<SteamGame>(ConnectionString);

    protected IRepository<LanguageIcons> LanguageIconsRepository => new Repository<LanguageIcons>(ConnectionString);

    protected IRepository<FileIcons> FileIconsRepository => new Repository<FileIcons>(ConnectionString);

    protected IRepository<FolderIcons> FolderIconsRepository => new Repository<FolderIcons>(ConnectionString);
}
⚠⚠    以下内容为AI分析的结果,请根据实际情况进行判断。

上述代码定义了一个名为 Basic 的抽象类,主要用于设置和配置一个依赖注入(DI)容器,以便在单元测试中使用。以下是代码的主要功能和组成部分的详细解释:

1. 依赖注入容器的配置

  • IServiceProvider _serviceProvider: 这是一个服务提供者,用于解析和获取服务实例。
  • ConfigurationBuilder: 通过读取 appsettings.Test.json 文件来构建配置对象,通常用于测试环境的配置。
  • IServiceCollection services: 创建一个服务集合,用于注册各种服务和依赖项。

2. 服务的注册

Basic 类的构造函数中,多个服务被注册到 DI 容器中,包括:

  • 配置服务: 将 IConfiguration 注册为单例,以便在应用程序中共享配置。
  • HTTP 客户端: 注册 HttpClient,用于发起 HTTP 请求。
  • 映射器: 注册 IMapper,用于对象之间的映射。
  • 工作单元和仓储: 注册 IUnitOfWorkIRepository<>,用于数据访问。
  • 业务服务: 注册多个业务服务,如 IAccountServiceIWaitExecutionService,这些服务包含业务逻辑。
  • Steam API 客户端: 注册 ISteamGameService,并配置其基础地址和 HTTP 消息处理程序。

3. 服务的获取

  • GetService<T>(): 这是一个通用方法,用于从服务提供者中获取指定类型的服务。如果服务未找到,则抛出异常。
  • ServiceProvider: 提供对 _serviceProvider 的访问,以便在子类中使用。

4. 连接字符串和配置

  • ConnectionString: 存储从配置中获取的 MongoDB 连接字符串。
  • Configuration: 提供对配置对象的访问。

5. 缓存提供者

  • CachingProviderHybridCachingProvider: 提供对 EasyCaching 的访问,虽然相关的缓存配置代码被注释掉了。

6. 仓储实例

  • 代码中定义了一些仓储属性(如 AppOptionRepository, CommentRepository 等),这些属性返回特定类型的仓储实例,使用 ConnectionString 进行初始化。

总结

Basic 类的主要目的是为单元测试提供一个配置良好的依赖注入环境。通过在构造函数中注册服务和配置,子类可以轻松地获取所需的服务和依赖项,从而进行测试。这个设计模式有助于提高代码的可测试性和可维护性。

loading