在MVC3中使用IOC容器是会话之间共享的对象吗?

时间:2012-05-02 14:16:21

标签: asp.net-mvc asp.net-mvc-3 session ioc-container

我已经阅读了几篇解释在MVC web应用程序中使用静态类的文章。 从这些文章中我创建了一个小例子来证明静态变量确实在用户会话之间共享。

我使用2种不同的浏览器,Windows身份验证和2个不同的用户帐户登录了我的网站。如果变量为null,则在用户登录时设置特定变量。 在第一个用户登录变量= 1之后。当我在用户2开始他的会话时访问它时,我可以清楚地看到这仍然是预期的= 1。到目前为止一切正常。

真正的问题是:我们正在使用一个名为MemoryContainer的IOC类。由于此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;
    }
}

1 个答案:

答案 0 :(得分:3)

由于您使用的是单例模式,因此只会创建MemoryContainer类的一个实例。这意味着无论何时触摸 Instance属性,您总是指向内存中的相同位置。因此,多个用户将共享相同的数据。

还应该注意,由于此类使用Dictionary<TKey, TValue>进行内部存储,因此该类不是线程安全的,除非您正确同步,否则不应在多线程环境(如ASP.NET应用程序)中使用访问此资源或使用线程安全的数据结构(例如ConcurrentDictionary<TKey, TValue>)。所以这个自定义构建的IoC容器很好,但是不应该在多线程应用程序中使用它而不使其成为线程安全的。