0

so i want to create some service that accesses external API, and i want to cache common requests from the API inside of that service, it depends on 3 other services, but i want to give it its own instance of cache, MemoryDistributedCache might later be changed for something else

services.AddSingleton<ISomeApi, SomeApi>(provider => new SomeApi(
    Configuration.Get<Options>(),
    new MemoryDistributedCache(new MemoryCache(new MemoryCacheOptions())),
    provider.GetService<ILogger<SomeApi>>()
    ));

now from my Controllers i can access the api via DI, it works nicely but im not sure if its some sort of an anti-pattern or if there are better ways of doing it

i mean the real problem is separating the internal cache, requesting IDistributedMemory from one service would give me the same object as if i request it from another service, they must be separated

2
  • 1
    Why does it need to be a separate cache? Also, just a note: GetService<T>() returns null if the service is not found. So if your service really needs the logger, use GetRequiredService<T>(). Commented Feb 14, 2017 at 7:32
  • lets say one cache is backed by one Database system, second cache is backed by another Commented Feb 14, 2017 at 15:57

1 Answer 1

1

This sounds like something you could use a proxy or decorator pattern for. The basic problem is that you have a service that does some data access, and another service responsible for caching the results of the first service. I realize you're not using a repository per se, but nonetheless the CachedRepository pattern should work for your needs. See here:

http://ardalis.com/introducing-the-cachedrepository-pattern and http://ardalis.com/building-a-cachedrepository-via-strategy-pattern

You can write your cached implementation such that it takes in the actual SomeApi type in its constructor if you don't need that part of the design to be flexible.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.