C# 如何访问只需在应用程序上创建一次的变量。开始
根据本指南: 他们说: 请注意,StackExchange.Redis客户端通过单个连接使用多路复用。建议的用法是在应用程序启动时创建客户端的实例,并将此实例用于针对缓存的所有操作。因此,到缓存的连接只进行一次,因此本节中的所有指导都与此初始连接的重试策略相关,而不是与访问缓存的每个操作相关 现在我有这样的事情:C# 如何访问只需在应用程序上创建一次的变量。开始,c#,azure,caching,stackexchange.redis,azure-redis-cache,C#,Azure,Caching,Stackexchange.redis,Azure Redis Cache,根据本指南: 他们说: 请注意,StackExchange.Redis客户端通过单个连接使用多路复用。建议的用法是在应用程序启动时创建客户端的实例,并将此实例用于针对缓存的所有操作。因此,到缓存的连接只进行一次,因此本节中的所有指导都与此初始连接的重试策略相关,而不是与访问缓存的每个操作相关 现在我有这样的事情: public static Models.UserProfile GetUserProfile(string identityname) {
public static Models.UserProfile GetUserProfile(string identityname)
{
/// It needs to be cached for every user because every user can have different modules enabled.
try
{
var cachekeyname = "UserProfileInformation|" + identityname;
IDatabase cache = CacheConnectionHelper.Connection.GetDatabase();
Models.UserProfile userProfile = new Models.UserProfile();
object obj = cache.Get(cachekeyname);
我可以将连接线移动到global.asax
protected void Application_Start()
{
IDatabase cache = CacheConnectionHelper.Connection.GetDatabase();
}
如果我移动这条线,那么我如何在需要使用它的其他方法上获得该实例
这是缓存连接帮助器
public class CacheConnectionHelper
{
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
return ConnectionMultiplexer.Connect(SettingsHelper.AzureRedisCache);
});
public static ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
}
}
公共类CacheConnectionHelper
{
私有静态懒散连接=新懒散(()=>
{
返回ConnectionMultiplexer.Connect(设置Shelper.AzureRedisCache);
});
公共静态连接多路复用器连接
{
得到
{
返回lazyConnection.Value;
}
}
}
您可以在global.asax文件中将其设置为静态
public class Global : HttpApplication {
public static IDatabase Cache = CacheConnectionHelper.Connection.GetDatabase();
void Application_Start(object sender, EventArgs e) {
}
.....
}
现在,只需访问数据库的单个实例Global.Cache
,即可访问任何类中的数据库对象