MVC6 dnx451对hasbind的Nhibernate nullreferenceexception

时间:2016-02-16 18:31:39

标签: asp.net-mvc nhibernate dnx

我正在使用dnx451将应用程序移动到MVC 6。尝试在nhibernate中打开一个新会话时,在检查当前上下文时会收到NullReferenceException。我正在使用WebSessionContext(可以看到堆栈跟踪);但是看起来上下文没有成功存储在HttpSession中。

Nhibernate目前是否适用于MVC 6?我目前在MVC 5中工作。最大的不同之处在于我如何获得会话。由于MVC 6不使用HttpModules,我已将会话的打开和关闭移动到过滤器属性(我可以看到的唯一缺点是,如果在视图中遇到某些属性,可能会出现延迟加载异常)。

过滤器代码如下:

public class DbTransactionAttribute:ActionFilterAttribute
    {
        private readonly IsolationLevel isolationLevel;

        /// <summary>
        /// Creates a transaction with IsolationLevel.ReadUncommitted
        /// </summary>
        public DbTransactionAttribute() {
            isolationLevel = IsolationLevel.ReadUncommitted;
        }

        public DbTransactionAttribute(IsolationLevel isolationLevel) {
            this.isolationLevel = isolationLevel;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext) {
            SessionManager.Instance.OpenSession();
            SessionManager.Instance.Session.BeginTransaction(isolationLevel);
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext) {
            ITransaction transaction = SessionManager.Instance.Session.Transaction;
            if (transaction.IsActive) {
                if (filterContext.Exception != null && filterContext.ExceptionHandled)
                    transaction.Rollback();
                else transaction.Commit();
            }
            transaction.Dispose();
            SessionManager.Instance.DisposeCurrentSession(); // We are finished with the session
        }
}

Startup mehod:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection(key: "Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(errorHandlingPath: "/Home/Error");
            }

            app.UseIISPlatformHandler();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            Nhibernate.Context.BuildContext(env);
            Nhibernate.SessionManager.BuildSessionManager(env);
        }

背景:

class Context {
        private static Context instance;

        private ISessionFactory sessionFactory;

        internal ISessionFactory SessionFactory { get { return sessionFactory; } }

        internal static Context Instance {
            get {
                if (instance == null) Initialize();
                return instance;
            }
        }

        internal static void BuildContext(Microsoft.AspNet.Hosting.IHostingEnvironment env) {
            if(instance == null) Initialize();
        }

        private static void Initialize() {
            instance = new Context();
            var hbrConfig = new NHibernate.Cfg.Configuration();
            var files = typeof(Context).Assembly.GetManifestResourceNames();
            hbrConfig.Configure(typeof(Context).Assembly, 
                resourceName: "Ppn.Web.Nhibernate.hibernate.cfg.xml");
            hbrConfig.AddAssembly(typeof(ProposalNumber).Assembly);

            instance.sessionFactory = hbrConfig.BuildSessionFactory();
        }
    }

SessionManager:

public class SessionManager : ISessionManager {
        private static ISessionFactory sessionFactory;

        private static SessionManager instance;

        public static SessionManager Instance {
            get {
                return instance ?? (instance = new SessionManager(Context.Instance.SessionFactory));
            }
        }

        public static void BuildSessionManager(Microsoft.AspNet.Hosting.IHostingEnvironment env) {
            if (instance == null) instance = new SessionManager(Context.Instance.SessionFactory);
        }

        public SessionManager(ISessionFactory sessionFactory) {
            SessionManager.sessionFactory = sessionFactory;
        }

        public ISession Session {
            get {
                bool hasBind = CurrentSessionContext.HasBind(sessionFactory); //Line that fails
                ISession result;
                if (hasBind) result = sessionFactory.GetCurrentSession();
                else result = OpenSession();
                return result;
                //return CurrentSessionContext.HasBind(sessionFactory) ? sessionFactory.GetCurrentSession() : OpenSession();
            }
        }

        public ISession OpenSession() {
            ISession session = sessionFactory.OpenSession();
            CurrentSessionContext.Bind(session);
            return session;
        }

        public void DisposeCurrentSession() {
            if (CurrentSessionContext.HasBind(sessionFactory)) {
                ISession session = CurrentSessionContext.Unbind(sessionFactory);
                session.Close();
                session.Dispose();
            }
        }
    }

例外:

NullReferenceException: Object reference not set to an instance of an object.

    lambda_method(Closure , Object )
    NHibernate.Context.ReflectiveHttpContext.get_HttpContextCurrentItems()
    NHibernate.Context.WebSessionContext.GetMap()
    NHibernate.Context.MapBasedSessionContext.get_Session()
    NHibernate.Context.CurrentSessionContext.HasBind(ISessionFactory factory)
    Ppn.Web.Nhibernate.SessionManager.get_Session() in SessionManager.cs
                        bool hasBind = CurrentSessionContext.HasBind(sessionFactory);
    Ppn.Web.Controllers.ProposalNumberController.Index() in ProposalNumberController.cs
                    ISession dbSession = SessionManager.Instance.Session;
    --- End of stack trace from previous location where exception was thrown ---

2 个答案:

答案 0 :(得分:2)

我找到了一个解决方案,我在其中创建了一个自定义ICurrentSessionContext,如下所示:

[Serializable]
public class Mvc6SessionContext: MapBasedSessionContext {
    private const string SessionFactoryMapKey = "NHibernate.Context.WebSessionContext.SessionFactoryMapKey";

    public Mvc6SessionContext(ISessionFactoryImplementor factory) : base(factory) {}

    protected override IDictionary GetMap() {
        return Context.Instance.HttpContext.Items[SessionFactoryMapKey] as IDictionary;
    }

    protected override void SetMap(IDictionary value) {
        Context.Instance.HttpContext.Items[SessionFactoryMapKey] = value;
    }
}

我们仍然需要获得对上下文的自定义访问权限。因此我只修改了我的应用程序的Context项目,如下所示:

class Context {
    private static Context instance;

    private ISessionFactory sessionFactory;
    private static IHttpContextAccessor contextAccessor;

    internal ISessionFactory SessionFactory { get { return sessionFactory; } }

    internal static Context Instance {
        get {
            if (instance == null) Initialize();
            return instance;
        }
    }

    internal HttpContext HttpContext {
        get { return contextAccessor.HttpContext; }
    }

    internal static void BuildContext(IApplicationBuilder app) {
        if(contextAccessor == null) contextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
        if (instance == null) Initialize();
    }

    private static void Initialize() {
        instance = new Context();
        var hbrConfig = new NHibernate.Cfg.Configuration();
        var files = typeof(Context).Assembly.GetManifestResourceNames();
        hbrConfig.Configure(typeof(Context).Assembly, 
            resourceName: "Ppn.Web.Nhibernate.hibernate.cfg.xml");
        hbrConfig.AddAssembly(typeof(ProposalNumber).Assembly);
        instance.sessionFactory = hbrConfig.BuildSessionFactory();
    }
}

在初创公司中,我传递了IApplicationBuilder

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection(key: "Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler(errorHandlingPath: "/Home/Error");
        }

        app.UseIISPlatformHandler();

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
        Nhibernate.Context.BuildContext(app);
        Nhibernate.SessionManager.BuildSessionManager(env);
    }

最后一件事是告诉Nhibernate在配置文件中使用我的实现:

<property name="current_session_context_class">Ppn.Web.Nhibernate.Mvc6SessionContext, Ppn.Web</property>

整个thig的语义应该与标准&#34; web&#34;相同。 Nhibernate中使用的密钥。我已经过测试,到目前为止一直很好。

要明确的是,这个项目是dnx451而不是.net核心(因为很多原因而无法工作)

答案 1 :(得分:0)

This告诉我NHibernate正在使用反射访问该属性。 Asp.Net.Core是一个重大改写,有很多重大变化,因此Asp.Net Core和之前版本之间没有确切的二进制/ API /功能奇偶校验。因此,使用以前版本的Asp.Net设计的许多项目将无法与Asp.Net.Core一起使用。