我正在构建一个 Web 应用程序,它使用一个外部构建的类来处理该站点的大部分工作和规则。大多数页面都需要访问这个类来获取它需要显示的信息。过去我会将这样的类放在会话变量中,因此在需要时可以轻松访问它,而无需不断地重新实例化。
第一个问题,将此类填充到会话变量中是不是一个坏主意(它不是很大)?
第二个问题,如果将站点应用程序层类存储在会话中不是一个坏主意,那么有没有办法可以编写一个集中的方法来将类获取或存储到会话中?我不想在页面获取类之后使用一堆重复的代码页,在那里检查它,如果不是就创建等等。
在决定将类存储在何处之前,您必须回答两个问题:
回答这两个问题的示例:请求、用户会话、应用程序。
如果这个类是无状态的(没有数据,只有逻辑),那么它可能会存在于应用程序的整个生命周期中。如果这只是每个用户独有的数据(不应在每个请求上重新加载),那么您可以将其直接放入会话并跳过以下段落。
现在,在你决定了生命长度之后,你有几个解决方案。生活方式管理的最佳解决方案是 IoC 容器。更简单的解决方案是抽象存储并使用静态外观,如 Current.MyClass,其中 MyClass 实例存储在请求、会话或应用程序中,具体取决于提供给 Current 的存储。
但是,您不应该在指定的类中实现单例,因为它本身不应该决定您需要多少个实例,并且如果需要,它会限制您替换具有相同接口的另一个类的能力。
在不知道您使用的任何框架的情况下,将一个类放入会话存储中似乎不是一个聪明的主意——它将为每个用户复制一次——除非它具有该用户独有的数据。
我能给出的最好建议是有一个单例类(你可以用谷歌搜索它——它是一种设计模式),然后在那个类中有一个函数,它会返回你需要的类,或者如果没有就创建它还存在。
是否应该首先将课程存储在会话中尚无定论。对于我提出问题的应用程序,我选择不将课程塞进会话中,这真的没有必要,我很懒惰。制定这种管理会话的方法一直都是值得的,因为它在 Web 开发中困扰了我一段时间。
我的研究结果是编写一个静态类来管理我的会话变量。这个类处理对会话的所有读取和写入,并保持它们都是强类型的,以便我启动。它一直困扰着我在整个地方使用重复的代码来进行会话废话。也减少了拼写错误。
我在此找到了两篇我喜欢的文章,我现在只能找到其中一篇,当我找到另一篇时会包括在内。
第一个是在Code Project 这可能是第二个链接
该模式简单明了。我还为从 url 查询字符串中获取参数的请求构建了一个类。我也没有理由不将其扩展到 cookie。
这是我第一次使用该模式,我只使用字符串,所以私有方法有点受限,但是可以很容易地更改为使用任何类或原始类型。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
namespace BDZipper.Site
{
/// <summary>
/// This class maintains all session variables for us instead of handeling them
/// individually in the session. They are also strongly typed.
/// </summary>
public static class SessionManager
{
# region Private Constants
// Define string constant for each property. We use the constant to call the session variable
// easier not to make mistakes this way.
// I think for simplicity, we will use the same key string in the web.config AppSettings as
// we do for the session variable. This way we can use the same constant for both!
private const string startDirectory = "StartDirectory";
private const string currentDirectory = "CurrentDirectory";
# endregion
/// <summary>
/// The starting directory for the application
/// </summary>
public static string StartDirectory
{
get
{
return GetSessionValue(startDirectory, true);
}
//set
//{
// HttpContext.Current.Session[startDirectory] = value;
//}
}
public static string CurrentDirectory
{
get
{
return GetSessionValue(currentDirectory, false);
}
set
{
HttpContext.Current.Session[currentDirectory] = value;
}
}
//TODO: Update to use any class or type
/// <summary>
/// Handles routine of getting values out of session and or AppSettings
/// </summary>
/// <param name="SessionVar"></param>
/// <param name="IsAppSetting"></param>
/// <returns></returns>
private static string GetSessionValue(string SessionVar, bool IsAppSetting)
{
if (null != HttpContext.Current.Session[SessionVar])
return (string)HttpContext.Current.Session[SessionVar];
else if (IsAppSetting) // Session null with appSetting value
return ConfigurationManager.AppSettings[SessionVar];
else
return "";
}
}
}