You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实例化带ICacheManager构造注入的RedisOperation类?

在ABP框架中正确实例化依赖ICacheManager的RedisOperation类

一、修正RedisOperation类的设计

你的RedisOperation无需继承AbpModule(模块类用于配置框架与依赖注入,业务服务不需要这个继承关系),同时要修正异步方法的返回类型(async void会导致异步异常无法被捕获,建议改用async Task):

public class RedisOperation
{
    private readonly string CacheKey = "RedisPOC";
    private readonly ICacheManager _cacheManager;

    // 仅保留带ICacheManager的构造函数,让DI容器自动完成注入
    public RedisOperation(ICacheManager cacheManager)
    {
        _cacheManager = cacheManager;
    }
    
    public async Task SetValueInCache(string input)
    {
        var lstInputs = await _cacheManager.GetCache(CacheKey).GetOrDefaultAsync(CacheKey);
        List<string> cacheInputStringList = lstInputs as List<string> ?? new List<string>();
            
        cacheInputStringList.Add(input);
        await _cacheManager.GetCache(CacheKey).SetAsync(CacheKey, cacheInputStringList);                        
    }

    public async Task ClearCache()
    {
        var cache = _cacheManager.GetCache(CacheKey);
        var lstInputs = await cache.GetOrDefaultAsync(CacheKey);            
        if (lstInputs != null)
            await cache.ClearAsync();
    }
}

二、创建ABP模块类配置依赖

需要一个模块类来初始化ABP框架、启用Redis缓存,并注册你的RedisOperation服务:

using Abp;
using Abp.Caching;
using Abp.Caching.Redis;
using Microsoft.Extensions.DependencyInjection;

[DependsOn(typeof(AbpCachingModule), typeof(AbpRedisCacheModule))]
public class RedisCacheDemoModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        // 将RedisOperation注册为可注入服务
        context.Services.AddTransient<RedisOperation>();
        
        // 配置Redis连接信息(根据你的Redis实例调整)
        Configure<AbpRedisCacheOptions>(options =>
        {
            options.ConnectionString = "localhost:6379";
            // 若Redis有密码,添加:options.Password = "你的Redis密码";
        });
    }
}

三、在Main方法中初始化ABP并获取实例

ABP框架需要先完成模块系统初始化,再从服务提供者中解析RedisOperation实例,不能直接new:

using System;
using System.Threading.Tasks;
using Abp;

class Program
{
    static async Task Main(string[] args)
    {
        // 初始化ABP应用程序
        using (var application = AbpApplicationFactory.Create<RedisCacheDemoModule>())
        {
            application.Initialize();
            
            // 从DI容器中获取RedisOperation实例(ICacheManager会被自动注入)
            var redisOp = application.ServiceProvider.GetRequiredService<RedisOperation>();

            Console.WriteLine("Redis Cache POC");
            Console.WriteLine("Choose below option to perform operation on RedisCache");
            Console.WriteLine("1. Add");
            Console.WriteLine("2. Clear");
            var input = Console.ReadLine();

            switch (int.Parse(input))
            {
                case 1:
                    Console.WriteLine("Enter text to add:");
                    string inputText = Console.ReadLine();
                    await redisOp.SetValueInCache(inputText);
                    Console.WriteLine("Added to cache successfully!");
                    break;
                case 2:
                    await redisOp.ClearCache();
                    Console.WriteLine("Cache cleared successfully!");
                    break;
                default:
                    Console.WriteLine("Invalid option!");
                    break;
            }
        }
    }
}

关键注意点

  • 禁止直接new RedisOperation():ABP的核心是依赖注入,ICacheManager是框架提供的内置服务,必须由DI容器创建并自动注入,不能手动实例化传递。
  • 模块的作用:AbpModule是ABP的扩展入口,用于配置服务、初始化框架组件(比如Redis缓存)。
  • 异步方法规范:业务代码中不要使用async void,改用async Task才能正确处理异步操作的异常与等待逻辑。

内容的提问来源于stack exchange,提问作者Programming

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:31:00