Skip to content

Singleton constraint conflict if IMemoryCache already exists #186

@LarsKemmann

Description

@LarsKemmann

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions