简体   繁体   中英

Multiple types of Distributed Cache in ASP.NET Core

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 ?

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM