2

Suppose I have a ASP.NET Core 2.x application.

I would like to use Redis for standard IDistributedCache dependency injection, but use SQL Server Distributed cache as the backing for Session middleware.

Is this possible? If so, how would you go about configuring this in Startup.cs?

1 Answer 1

1

The distributed session state storage injects the IDistributedCache instance by default. This means you should configure the SQL Server distributed cache as the default one if you would like to use that for session state.

For your own caching purposes, you could create a "wrapper interface" which specifically represents the Redis cache (such as IRedisCache), register it and inject that in your middleware/controllers/services. For example:

public interface IRedisDistributedCache : IDistributedCache
{
}

public void ConfigureServices(IServiceCollection services)
{
    // Add Redis caching
    services.AddDistributedRedisCache();
    services.AddSingleton<IRedisDistributedCache, RedisCache>();

    // Add SQL Server caching as the default cache mechanism
    services.AddDistributedSqlServerCache();
}

public class FooController : Controller
{
    private readonly IRedisDistributedCache _redisCache;

    public FooController(IRedisDistributedCache redisCache)
    {
        _redisCache = redisCache;
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

How would you initialize the Redis instance in this case? Normally, I've initialized it in services.AddDistributedRedisCache() call.
@user1142433 see the code example. I'm calling AddDistributedRedisCache() just like you normally would, and afer that bind RedisCache implemenation to the IRedisDistributedCache "wrapper interface".
So you're adding two IDistributedCache cache items to the DI service (one Redis and one SQL based)? And when Session calls for an IDistributedCache implementation it gets the SQL version because you added it to the service config after the Redis version? In other words, how does the service resolver decide which IDistributedCache it gives to the Service middleware?
@user1142433 that's correct. The container will pick the last one you registered.
I see now how it should work in principle. Unfortunately, the sample won't compile because "There is no implicit conversion from RedisCache to IRedisDistributedCache" on line services.AddSingleton<IRedisDistributedCache, RedisCache> ();
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.