如何访问我只需要在 Application.Start 上创建一次的变量

How to access a variable that I only need to create once on Application.Start

根据本指南: https://github.com/mspnp/azure-guidance/blob/master/Retry-Service-Specific.md

他们说:

请注意,StackExchange.Redis 客户端通过单个连接使用多路复用。推荐的用法是在应用程序启动时 创建一个客户端实例 并将此实例用于针对缓存的所有操作。出于这个原因,与缓存的连接只建立一次,因此本节中的所有指导都与此初始连接的重试策略相关——而不是与访问缓存的每个操作相关。

现在我有这样的东西:

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;
            }
        }
    }

您可以在 global.asax 文件中将其设为静态

public class Global : HttpApplication {
    public static IDatabase Cache = CacheConnectionHelper.Connection.GetDatabase();
    void Application_Start(object sender, EventArgs e) {

    }
    .....
}

现在您可以通过简单地访问 Global.Cache 来访问任何 class 中的数据库对象,这是您的单个数据库实例。