C# – Database Context and Singleton injection with IoC

asp.netcinversion-of-controlsql

All of the below relates to a ASP.NET c# app.
I have a Singleton Settings MemoryCache that reads values from database on first access and caches these, then invalidates them using SQL Service Broker message and re-reads as required.

For the purposes of standard controllers, i create my Db Context in a request scope.
However, this obviously means that i can't use the same context in the Settings Cache class, since that is a singleton and we have a scope collision.

At the moment, i ended up with two db contexts – the Controllers get it via IoC container, whereas a Singleton just creates it's own.

However, i am not satisfied with this approach (mostly due to the way i feel about two contexts, the cache doesn't set anything on the db hence concurrency is not an issue as much).

What is a better way to do it?

Best Answer

You could split your cache implementation into 2 parts, a Cache and a CacheStorage.

The CacheStorage is only responsible for storing the cached data, and has a Singleton lifetime. Because it may be accessed by multiple threads concurrently, it should be thread-safe.

The Cache is the dynamic part of the caching mechanism, it has a PerRequest lifecycle and depends on both the CacheStorage and the DbContext. It is responsible for reading the settings from the DbContext on first access and updating the CacheStorage's data with it.

This way, the CacheStorage can be kept on for the duration of the application, and the Cache gets instantiated only when there's a valid DbContext available.

Related Topic