首页 > 解决方案 > 如何在业务类中注入 IDistributedCache

问题描述

我有一个 asp.net 核心项目,我正在尝试使用IDistributedCache(Redis)。

我想IDistributedCache在自定义类中访问,而不仅仅是在控制器中。

那可能吗?

标签: c#asp.net-coredependency-injectionredis

解决方案


我想在自定义类中访问 IDistributedCache,而不仅仅是在控制器中。那可能吗?

是的。

注册服务集合

var redisconnection = "...";
services.AddDistributedRedisCache(o => { o.Configuration = redisconnection; });
services.AddScoped<MyCustomClass>();

//...

并将其作为自定义类的可注入参数

public MyCustomClass(IDistributedCache cache) {
    //...
}

推荐阅读