Jeppe
Jeppe

Reputation: 1563

Caching and lifetime in ASP.NET Web API

I have a WCF project where I have some dependencies that are really expensive to start up, as in 2+ seconds per call. The dependencies are instantiated with a sting pair, kind of like username/password, so they can't just be reused in a pool between calls to the API.

Currently we are not using dependency injection and I want to rewrite the project as an ASP.NET Web API project with DI and a cache so we have the dependencies with the most common string pairs already loaded into memory.

I would like help with the two main components of this problem.

Upvotes: 0

Views: 44

Answers (1)

ste-fu
ste-fu

Reputation: 7482

It's important to consider the difference in lifetime between a cache and a DI container, as the easiest answer will largely depend on the number of different instances of your expensive dependency you have.

DI containers typically have 3 scopes or lifetimes

  • A new instance every time a dependency is resolved (transient)
  • A new instance per call into the application (scoped)
  • One instance in the lifetime of the application (singleton)

A cache contains potentially millions of records, each of which has a Time To Live or Expiry, which may or may not be refreshed upon a cache retrieval.

If you only have a few expensive dependencies then it makes sense to register them in the DI container as keyed services, they will all get created when the app starts up and they can be retrieved from the container via their key.

If you are going to have lots of instances, perhaps one per user with a large number of concurrent users, then a cache is the way to go. The simplest implementation is to use an IMemoryCache but there are other options available. IMemoryCache has a method GetOrCreate or GetOrCreateAsync. If your dependencies are complex and you want to make this work with DI then you can wrap the IMemoryCache in a class and inject a factory class into it to aid in object creation.

Upvotes: 1

Related Questions