Distributed cache implemented with MongoDB using Official .NET driver for MongoDB.
This implementation is based on the official version for Sql Server and Redis available here.
- Add package Frcs6.Extensions.Caching.MongoDB.
- Inject Mongo cache using
MongoCachingServicesExtensions.AddMongoCache
. - Use
IDistributedCache
where you need it.
Some examples are available here.
You can inject Mongo cache using MongoCachingServicesExtensions.AddMongoCache
method with one of these parameters :
ConnectionString
.MongoClientSettings
.IMongoClient
.
MongoClientSettings
can be useful if you need to pass a certificate. You can read the official Mongo documentation Enable TLS on a Connection.
const string connectionString = "mongodb://localhost:27017";
builder.Services.AddMongoCache(connectionString, options =>
{
options.DatabaseName = "MyCacheDatabase";
options.CollectionName = "MyCacheCollection";
options.RemoveExpiredDelay = TimeSpan.FromSeconds(10);
});
var cert = new X509Certificate2("client.p12", "mySuperSecretPassword");
var settings = new MongoClientSettings
{
SslSettings = new SslSettings
{
ClientCertificates = new[] { cert }
},
UseTls = true
};
builder.Services.AddMongoCache(settings, options =>
{
options.DatabaseName = "MyCacheDatabase";
options.CollectionName = "MyCacheCollection";
options.RemoveExpiredDelay = TimeSpan.FromSeconds(10);
});
DatabaseName
: Name of the cache database (required).CollectionName
: Name of the cache collection (required).AllowNoExpiration
: Allow item without expiration (default false).RemoveExpiredDelay
: Delay between each cache clean (default null).
Removing expired elements is automatic. The only option you have to set is RemoveExpiredDelay
.
If RemoveExpiredDelay
is not set, cleaning will launch on each cache access (Get, Set, Refresh).