nhibernatelazy-loadingisession

nhibernate lazyload creates new isession


Can I prevent nhibernate creating new ISessions when lazy loading? How?

Correction: I mean new IDbConnections. I have implemented my own DriverConnectionProvider and I see it gets called due to lazy loading


Solution

  • If you are using NHibernate as a connection manager and sql generator. I.e. you have a lot of code like the following:

    public IList<Entity> GetEntities()
    {
        using (ISession session = CreateNewSession())
        {
            return session.List<Entity>();
        }
    }
    

    Then you cannot use lazy loading. So you will need to disable lazy loading. This can be most easily achieved by specifying default-lazy="false" on your hibernate-mapping tag http://nhibernate.info/doc/nh/en/index.html#mapping-declaration-mapping

    I might recommend using an IStatelessSession instead of the default ISession as well. Keep in mind that this is not the recommended use of NHibernate.