简体   繁体   中英

C# Azure Redis Cache - Cannot access a disposed object exception

Followed the below link to implement Redis Cache in Web API. https://docs.microsoft.com/en-us/azure/redis-cache/cache-dotnet-how-to-use-azure-redis-cache

The Cache works fine for the first time but fails with the error

"Cannot access a disposed object"

...on the subsequent reads.

As mentioned in the above blog, I am disposing the connection at the end of the method and invoking the method again throwing the above exception: lazyConnection.Value.Dispose();

Also tried to encapsulate the connection attributes in a different class, as mentioned here. But as they are declared static, the same value retain across all the instances and so when disposing the connection leads to the same exception on the subsequent call.

https://www.c-sharpcorner.com/article/using-redis-cache-in-web-api/

There are a couple of ways I can fix this:

  1. Do not dispose the connection and reuse the same connection for all the calls.

  2. Make the Cache connection non-static, so that a new connection gets created and disposed for every call.

What is the right way of doing this?

You should not create a connection on every call, that will be very inefficient. A static connection should also be avoided if possible. It can make unit tests harder to write and prevents you having multiple connections within the same process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM