Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Singleton constraint conflict if IMemoryCache already exists #186

Open
LarsKemmann opened this issue Mar 3, 2023 · 0 comments
Open

Singleton constraint conflict if IMemoryCache already exists #186

LarsKemmann opened this issue Mar 3, 2023 · 0 comments
Labels

Comments

@LarsKemmann
Copy link

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:
CareTogether/CareTogetherCMS@076200d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant