9

I am new to Redis and using VS 2015 and the ASP.NET Core app (v 1.0), I installed the nugget package:

Install-Package StackExchange.Redis

However I am not able to inject and configure it into my services, there is no RedisCache or "AddDistributedRedisCache" method.

How can I inject and use it?

Hussein Salman
  • 7,806
  • 15
  • 60
  • 98
  • Did you actually wanted to use `Microsoft.Extensions.Caching.Redis` instead, which is out-of-the-box redis support for distributed caching? It's one of the 3 default implementations of `IDistrubutedCache` interface https://github.com/aspnet/Caching/tree/1.0.0/src – Tseng Nov 01 '16 at 20:50
  • I installed **Microsoft.Extensions.Caching.Redis** at the first moment but its not compatible with .NET Core it needs Framework 4.5+ I guess. – Hussein Salman Nov 01 '16 at 20:52
  • `StackExchange.Redis` only contains a redis client, it do not implement itself into ASP.NET Core. But Microsoft`s distributed caching implementation uses `Microsoft.Extensions.Caching.Redis`, its just a wrapper around it and the `IDistrubtedCache` interface. github.com/aspnet/Caching/blob/dev/src/Microsoft.Extensions.Caching.Redis/RedisCache.cs – Tseng Nov 01 '16 at 20:53
  • 2
    Yes, that's right. Didn't noticed it earlier. Next version will support it. Currently there is a package, but for ASP.NET Core 1.1-preview1. I think its because Stackexchange.Redis wasn't having RTM Version for .NET Core when Microsoft went RTM with ASP.NET Core – Tseng Nov 01 '16 at 20:55
  • I guess, if you grab the source from https://github.com/aspnet/Caching/tree/1.0.0/src/Microsoft.Extensions.Caching.Redis and retarget it for .NET Core with a .NET Core compatible version of StackExchange.Redis package, you should get it working. The Caching.Redis package doesn't contain much code, just wrapps roughly around the SE.Redis client. Then you can use it right now instead of upgrading to the ASP.NET Core 1.1-preview which isn't production ready – Tseng Nov 01 '16 at 20:58
  • I tried to resolve and started changing the dependencies. I started from the `Micorosoft.Extensions.Caching.Abstratctions` project, since Redis class library references it. However I ran into problems, since I cannot resolve one of the dependencies, check this [question](http://stackoverflow.com/questions/40386962/trying-to-resolve-dependencies-changing-net-standard-library-to-net-core) – Hussein Salman Nov 02 '16 at 18:16
  • Use https://www.nuget.org/packages/Microsoft.Extensions.Caching.Redis.Core/ instead of the one (without Core) I guess for .Net core stuff... If you want to have more functionatliy then just Set/Get with byte arrays, give www.cachemanager.net a try. – MichaC Dec 22 '16 at 22:48

3 Answers3

12

01.Download latest redis from download ,install and start the redis service from services.msc

02.Add two library in project.json

"Microsoft.Extensions.Caching.Redis.Core": "1.0.3",
"Microsoft.AspNetCore.Session": "1.1.0",

03.Add you dependency injection in

public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddMvc();
        //For Redis
        services.AddSession();
        services.AddDistributedRedisCache(options =>
        {
            options.InstanceName = "Sample";
            options.Configuration = "localhost";
        });
  } 
  1. and in Configure method add top of app.UseMvc line

    app.UseSession();

to use redis in session storage in asp.net core .Now you can use like this in HomeController.cs

public class HomeController : Controller
{
    private readonly IDistributedCache _distributedCache;
    public HomeController(IDistributedCache distributedCache)
    {
        _distributedCache = distributedCache;
    }
    //Use version Redis 3.22
    //http://stackoverflow.com/questions/35614066/redissessionstateprovider-err-unknown-command-eval
    public IActionResult Index()
    {
        _distributedCache.SetString("helloFromRedis", "world");
        var valueFromRedis = _distributedCache.GetString("helloFromRedis");
        return View();
    }
 }
Syed Mhamudul Hasan
  • 1,341
  • 2
  • 17
  • 45
3

I used the following solution and got the answer.

1.Download Redis-x64-3.0.504.msi and install it (link)

2.Install Microsoft.Extensions.Caching.StackExchangeRedis from Nuget Packge Manager

3.Inside the Startup.cs class ,In the ConfigureServices method, add this command:

 services.AddStackExchangeRedisCache(options => options.Configuration = "localhost:6379");
  1. inject IDistributedCache to the controller:

     private readonly IDistributedCache _distributedCache;
    
     public WeatherForecastController( IDistributedCache distributedCache)
     {
         _distributedCache = distributedCache;
     }
    

5.In the end:

   [HttpGet]
    public async Task<List<string>> GetStringItems()
    {
        string cacheKey = "redisCacheKey";
        string serializedStringItems;
        List<string> stringItemsList;

        var encodedStringItems = await _distributedCache.GetAsync(cacheKey);
        if (encodedStringItems != null)
        {
            serializedStringItems = Encoding.UTF8.GetString(encodedStringItems);
            stringItemsList = JsonConvert.DeserializeObject<List<string>>(serializedStringItems);
        }
        else
        {
            stringItemsList = new List<string>() { "John wick", "La La Land", "It" };
            serializedStringItems = JsonConvert.SerializeObject(stringItemsList);
            encodedStringItems = Encoding.UTF8.GetBytes(serializedStringItems);
            var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(1))
                .SetAbsoluteExpiration(TimeSpan.FromHours(6));
            await _distributedCache.SetAsync(cacheKey, encodedStringItems, options);

        }
        return stringItemsList;
    }

Good luck!!!

0
Install-Package StackExchange.Redis

Redis service:

public class RedisService : IDisposable
{
    private readonly IConnectionMultiplexer Connection;
    private readonly string _connectionString;


    public RedisService(IConfiguration Configuration, ILogger<RedisService> logger)
    {
        _connectionString = Configuration.GetConnectionString("redis connection string");

        var conn = new Lazy<IConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(_connectionString));
        Connection = conn.Value;

        Main = Connection.GetDatabase(1); 


        logger.LogWarning("Redis Service Attached!");

    }

    public IDatabase Main { get; }

   
    
    public void Dispose()
    {
        Connection?.Dispose();
    }
}

add service in startup.cs

services.AddSingleton<RedisService>();

now use it in your Controller

foad abdollahi
  • 1,733
  • 14
  • 32