我已经阅读了几篇解释在 MVC Web 应用程序中使用静态类的文章。从这些文章中,我创建了一个小示例来证明静态变量确实在用户会话之间共享。
我使用 2 个不同的浏览器、Windows 身份验证和 2 个不同的用户帐户登录到我的站点。如果变量为空,则在用户登录时设置特定变量。在第一个用户登录变量 = 1 之后。当我在用户 2 开始他的会话时访问它时,我可以清楚地看到它仍然 = 1,正如预期的那样。到目前为止,它工作正常。
真正的问题是:我们正在为 IOC 使用一个名为 MemoryContainer 的类。由于这个 Memorycontainer 类的一部分是静态的,在这个容器中注册的类是否也在 mvc 中的用户会话之间共享?
完整代码:
public class MemoryContainer
{
#region Singleton
private static volatile MemoryContainer instance;
private static object syncRoot = new Object();
private MemoryContainer()
{}
private void Initialize()
{
myContainer = new Dictionary<Type, object>();
}
public static MemoryContainer Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new MemoryContainer();
instance.Initialize();
}
}
}
return instance;
}
}
#endregion
Dictionary<Type, object> myContainer = null;
private Dictionary<Type, object> Container
{
get { return this.myContainer; }
}
public void RegisterInstance(Type type, object instance)
{
if (!myContainer.ContainsKey(type))
myContainer.Add(type, instance);
}
public void UpdateInstance(Type type, object newInstance)
{
if (this.myContainer.ContainsKey(type))
myContainer[type] = newInstance;
}
public T Resolve<T>(Type t) where T : class
{
T item = (T) myContainer[t];
myContainer.Remove(t);
return item;
}
public T TryResolve<T>(Type t) where T : class
{
if (this.myContainer.ContainsKey(t))
return (T) Resolve<T>(t);
return null;
}
public T Peek<T>(Type t) where T : class
{
if (this.myContainer.ContainsKey(t))
return (T) myContainer[t];
return null;
}
}