Application_BeginRequest() 未将对象引用设置为对象的实例

发布于 2024-10-08 07:43:51 字数 4809 浏览 6 评论 0原文

尝试创建连接时,我的 MVC 应用程序出现错误。我正在使用 NHibenate 和 Ninject。

Global.asax.cs 文件:

namespace Web.UI
{
    public class MvcApplication : NinjectHttpApplication // System.Web.HttpApplication
    {
        public static ISessionFactory SessionFactory { get; set; }

        public void CreateSessionFactory()
        {
            SessionFactory = (new Configuration()).Configure().BuildSessionFactory();
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }

        protected override IKernel CreateKernel()
        {
            return new StandardKernel(new MvcApplicationModule());
        }

        protected override void OnApplicationStarted()
        {
            RegisterRoutes(RouteTable.Routes);
        }

        protected override void OnApplicationStopped()
        {
            SessionFactory.Dispose();
        }

        protected void Application_BeginRequest()
        {
            var sessionFactory = SessionFactory.OpenSession();
            CurrentSessionContext.Bind(sessionFactory);
        }

        protected void Application_EndRequest()
        {
            CurrentSessionContext.Unbind(SessionFactory);
        }
    }

    internal class MvcApplicationModule : NinjectModule
    {
        public override void Load()
        {

            // NHibernate Session
            Bind<ISession>().ToMethod(ctx => MvcApplication.SessionFactory.GetCurrentSession());

            Bind<IManagerRepository>().To<ManagerRepositoryImpl>();
        }
    }
}

Web.config 文件:

  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <!--
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      -->
      <property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
      <property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
      <property name="connection.connection_string_name">MyConnString</property>
      <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory,NHibernate.ByteCode.Castle</property>
      <property name="current_session_context_class">web</property>
      <mapping assembly="Infrastructure"/>
    </session-factory>
  </hibernate-configuration>

这是错误消息:

Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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

Source Error:

Line 57:         protected void Application_BeginRequest()
Line 58:         {
Line 59:             var sessionFactory = SessionFactory.OpenSession();
Line 60:             CurrentSessionContext.Bind(sessionFactory);
Line 61:         }

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   Web.UI.MvcApplication.Application_BeginRequest()

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +0
   System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +71
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +350
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +29
   System.Web.Util.ArglessEventHandlerProxy.Callback(Object sender, EventArgs e) +42
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75


Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053 

I am getting an error in my MVC Application when trying to create a connection. I'm using NHibenate along with Ninject.

Global.asax.cs file:

namespace Web.UI
{
    public class MvcApplication : NinjectHttpApplication // System.Web.HttpApplication
    {
        public static ISessionFactory SessionFactory { get; set; }

        public void CreateSessionFactory()
        {
            SessionFactory = (new Configuration()).Configure().BuildSessionFactory();
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }

        protected override IKernel CreateKernel()
        {
            return new StandardKernel(new MvcApplicationModule());
        }

        protected override void OnApplicationStarted()
        {
            RegisterRoutes(RouteTable.Routes);
        }

        protected override void OnApplicationStopped()
        {
            SessionFactory.Dispose();
        }

        protected void Application_BeginRequest()
        {
            var sessionFactory = SessionFactory.OpenSession();
            CurrentSessionContext.Bind(sessionFactory);
        }

        protected void Application_EndRequest()
        {
            CurrentSessionContext.Unbind(SessionFactory);
        }
    }

    internal class MvcApplicationModule : NinjectModule
    {
        public override void Load()
        {

            // NHibernate Session
            Bind<ISession>().ToMethod(ctx => MvcApplication.SessionFactory.GetCurrentSession());

            Bind<IManagerRepository>().To<ManagerRepositoryImpl>();
        }
    }
}

Web.config file:

  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <!--
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      -->
      <property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
      <property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
      <property name="connection.connection_string_name">MyConnString</property>
      <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory,NHibernate.ByteCode.Castle</property>
      <property name="current_session_context_class">web</property>
      <mapping assembly="Infrastructure"/>
    </session-factory>
  </hibernate-configuration>

This is the error message:

Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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

Source Error:

Line 57:         protected void Application_BeginRequest()
Line 58:         {
Line 59:             var sessionFactory = SessionFactory.OpenSession();
Line 60:             CurrentSessionContext.Bind(sessionFactory);
Line 61:         }

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   Web.UI.MvcApplication.Application_BeginRequest()

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +0
   System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +71
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +350
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +29
   System.Web.Util.ArglessEventHandlerProxy.Callback(Object sender, EventArgs e) +42
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75


Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

日暮斜阳 2024-10-15 07:43:51

Global.asax.cs

protected override void OnApplicationStarted()
{
    RegisterRoutes(RouteTable.Routes);
    CreateSessionFactory();
}

Global.asax.cs

protected override void OnApplicationStarted()
{
    RegisterRoutes(RouteTable.Routes);
    CreateSessionFactory();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文