Finbuckle.MultiTenant
Finbuckle.MultiTenant copied to clipboard
Tenant caching
Hi,
this is my code to cache a tenant in the DistributedMemoryCache
once resolved, in order to skip the more expensive database call.
It seems to work but, since I have assembled this code from various issues here on GitHub, @AndrewTriesToCode can you please tell me if it complies with best practices? Thank you.
builder.Services.AddDistributedMemoryCache();
builder.Services.AddMultiTenant<MyTenantInfo>(config =>
{
config.Events.OnTenantResolved = async (context) =>
{
if (context.StoreType != typeof(DistributedCacheStore<MyTenantInfo>))
{
var sp = ((HttpContext)context.Context).RequestServices;
var distributedCacheStore = sp
.GetService<IEnumerable<IMultiTenantStore<MyTenantInfo>>>()
.FirstOrDefault(s => s.GetType() == typeof(DistributedCacheStore<MyTenantInfo>));
await distributedCacheStore.TryAddAsync((MyTenantInfo)context.TenantInfo);
}
await Task.FromResult(0);
};
})
.WithDistributedCacheStore(TimeSpan.FromMinutes(60))
.WithEFCoreStore<MultiTenantStoreDbContext, MyTenantInfo>()
// some more stuff
@devalot76 this looks good to me. I'd like to make this more seamless in the future and it's on the list...
Would certainly be a good addition to prevent silly situations like the one I have just discovered. While trying to figure out why I was getting so many (Azure) Redis timeouts, I realized that I forgot to add a check the likes of if (context.StoreType == typeof(DistributedCacheStore<MyTenantInfo>)) return;
in the OnTenantResolved
callback, resulting in a massive and utterly unnecessary inefficiency in the synchronization process between the database and Redis cache.
@hbulens I'm glad you caught that. I definitely would want it to be smart enough to avoid that type of issue.