user1142433
user1142433

Reputation: 1551

ASP.NET Core multiple Dependency Injection with multiple interfaces

Running ASP.NET Core 2.x and I'm trying to register two types of IDistributedCache services (both ship in the box).

I'd like to use the SQL Distributed Cache for Sessions and the local DistributedMemory cache for everything else (eventually this will be a redis cache, but that's irrelevant at the moment).

        // Distributed Cache used for Sessions
        services.AddDistributedSqlServerCache(o => //  IDistributedCache with SQL backed storage version
        {
            o.ConnectionString = dbCs;
            o.SchemaName = "dbo";
            o.TableName = "Sessions";
        });

        services.AddDistributedMemoryCache();

As it stands, both of these resolve to IDistributedCache. Is it possible to direct the Sessions middleware to use the SQL cache and everything else to resolve to DistributedMemoryCache?

Upvotes: 1

Views: 830

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239220

Out of the box, no, this is not going to be possible. Microsoft.Extensions.DependencyInjection is very basic. You can register multiple implementations of an interface, but the only way to logically use them at that point is to inject all the implementations, via something like List<IDistributedCache> in this case. The distribute caching machinery doesn't support this, though.

It might, and I stress might, be possible if you use a more advanced DI container like Autofac, but I've never tried this scenario, and therefore cannot say for sure.

That said, it should be noted that caching isn't designed to be segregated like this. Session storage in ASP.NET Core uses cache because it's temporal by nature, and lends itself more readily to ejecting expired or no longer relevant entries than a relational database does, not withstanding the fact that you're actually backing the cache with a relational database in this circumstance. Regardless, you're intended to just have one cache, not multiple different caches with different backing stores. Session storage will work just as well in Redis (if not better), so I don't see a strong need for this anyways.

Upvotes: 1

Related Questions