LazyCache
LazyCache copied to clipboard
Singleton constraint conflict if IMemoryCache already exists
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
- OS: Windows 10
- Framework: .NET 6
- LazyCache Version: LazyCache.AspNetCore 2.4.0
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