如何在asp.net mvc中访问全局变量

时间:2012-07-15 20:31:43

标签: c# asp.net-mvc-3

我正在尝试访问在项目的Global.asax部分中设置的全局变量。在我的DAL中包含命名空间并访问变量visual studio抱怨。这是代码

protected void Application_Start()
{
     AreaRegistration.RegisterAllAreas();
     RegisterGlobalFilters(GlobalFilters.Filters);
     RegisterRoutes(RouteTable.Routes);
     Application["NHSessionFactory"] = CreateSessionFactory();
}

这是我的DAL逻辑

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using NHibernate;

namespace Data.DAL
{
    public class DB
    {
        private ISessionFactory session;
        public DB()
        {
            ISessionFactory session = (ISessionFactory) Application["NHSessionFactory"];   //problems here
        }

        public ISessionFactory GetSession()
        {
            return session;
        }
    }
}

错误的屏幕截图: enter image description here

我如何访问Global.asax中设置的变量?

1 个答案:

答案 0 :(得分:0)

是的,你可以像asp.net一样使用Application变量

Example:

System.Web.HttpContext.Current.Application.Lock();
System.Web.HttpContext.Current.Application["NHSessionFactory"] = "Something";
System.Web.HttpContext.Current.Application.UnLock();