使用autofac在asp.net webforms中进行nhibernate session-per-request

时间:2012-02-17 15:57:15

标签: nhibernate autofac session-per-request

我正在寻找如何实现Session-per-request模式来管理Asp.net webforms中的nhibernate会话。我在Application_EndRequest事件中遇到了nhibernate会话的问题,因为她关闭了。问题的循环如下:
1. Application_BeginRequest - 会话存在,我打开交易
2. Application_EndRequest - 会话关闭,发生异常:会话已关闭

知道为什么会这样吗?我没有使用nhibernate上下文,因为我必须将ISession注入存储库。

public class Global : System.Web.HttpApplication, IContainerProviderAccessor, Interfaces.IContainerProvider
{
    // Provider that holds the application container.
    static Autofac.Integration.Web.IContainerProvider _containerProvider;

    // Instance property that will be used by Autofac HttpModules
    // to resolve and inject dependencies.
    public Autofac.Integration.Web.IContainerProvider ContainerProvider
    {
        get { return _containerProvider; }
    }

    public IContainer ApplicationContainer
    {
        get { return _containerProvider.ApplicationContainer; }
    }

    protected void Application_Start(object sender, EventArgs e)
    {
        // Build up your application container and register your dependencies.
        var builder = new ContainerBuilder();
        builder.RegisterModule(new WebsiteModule());
        builder.RegisterInstance(this).As<Interfaces.IContainerProvider>();

        _containerProvider = new ContainerProvider(builder.Build());
        AutofacServiceHostFactory.Container = _containerProvider.ApplicationContainer;
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        ISession session = ContainerProvider.RequestLifetime.Resolve<ISession>();
        session.BeginTransaction();
    }

    private void Application_EndRequest(object sender, EventArgs e)
    {
        ISession session = ContainerProvider.RequestLifetime.Resolve<ISession>();

        if (session != null)
        {
            try
            {
                session.Transaction.Commit();
            }
            catch (Exception)
            {
                session.Transaction.Rollback();
            }
            finally
            {
                session.Close();
            }
        }
    }
}

我以这种方式注册NHibernate ISession:

builder.Register(x => x.Resolve<ISessionFactory>().OpenSession()).As<ISession>().InstancePerLifetimeScope();

0 个答案:

没有答案