-
redis 如何在构造函数中,使用依赖注入作者 : Jacky 发布于 2023-05-29 14:12:21 浏览 545 次
使用前记得 安装nuget包 xiaofeng.redis
using XiaoFeng.Redis; var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton<IRedisClient>(new RedisClient("redis://172.168.1.111:6379/0?ConnectionTimeout=3000&ReadTimeout=3000&SendTimeout=3000&pool=3"));
然后在你的控制器里进行实例化
/// <summary> /// /// </summary> private readonly IRedisClient _redisClient; /// <summary> /// /// </summary> /// <param name="ftpClient"></param> public ManageController(IRedisClient redisClient) { _redisClient = redisClient; } /// <summary> /// 测试redis /// </summary> [HttpGet] public void TestReis() { var lll = _redisClient.SetString("111", "222"); var ll1l = _redisClient.GetString("111"); }
如果想在
Program.cs
写的更简洁一下,
例如想这样写var builder = WebApplication.CreateBuilder(args); builder.Services.AddRedisCacheSetup();
我们需要写一个静态类
/// <summary> /// Redis缓存 启动服务 /// </summary> public static class RedisCacheSetup { public static void AddRedisCacheSetup(this IServiceCollection services) { if (services == null) throw new ArgumentNullException(nameof(services)); services.AddSingleton<IRedisClient>(new RedisClient("redis://172.16.29.104:6379/0?ConnectionTimeout=3000&ReadTimeout=3000&SendTimeout=3000&pool=3")); } }
所有评论(0)