alastairtree / LazyCache

An easy to use thread safe in-memory caching service with a simple developer friendly API for c#
https://nuget.org/packages/LazyCache
MIT License
1.71k stars 159 forks source link

Singleton constraint conflict if IMemoryCache already exists #186

Open LarsKemmann opened 1 year ago

LarsKemmann commented 1 year ago

Describe the bug If I have (directly or indirectly) already registered an IMemoryCache instance with the DI container, then services.AddLazyCache() fails with the following exception:

System.Security.VerificationException: Method Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton: type argument 'Microsoft.Extensions.Caching.Memory.MemoryCache' violates the constraint of type parameter 'TImplementation'.

To Reproduce

services.AddSingleton<IMemoryCache>(new MemoryCache(Options.Create(new MemoryCacheOptions())));
services.AddLazyCache();

Expected behavior Ideally, AddLazyCache would to try to use any existing global IMemoryCache instance if one already exists, rather than expecting that it is always the first library to register its IMemoryCache singleton. I realize that this puts the burden of managing that IMemoryCache on the client, but that would be a given anyways.

Framework and Platform

Additional context I ran into this because the NSwag library/CLI injects an IMemoryCache during its OpenAPI model generation process before my Startup.cs is ever invoked. Here is the commit of the workaround that I had to use: https://github.com/CareTogether/CareTogetherCMS/commit/076200d81c4c8ca868fd9f83c2d8122fd6339ff4