nhibernate sessionfactory instance more than once on web service

Posted by Manuel on Stack Overflow See other posts from Stack Overflow or by Manuel
Published on 2011-01-14T13:37:34Z Indexed on 2011/01/14 21:53 UTC
Read the original article Hit count: 196

Hello, i have a web service that use nhibernate. I have a singleton pattern on the repositorry library but on each call the service, it creates a new instance of the session factory wich is very expensive. What can i do?

region Atributos

    /// <summary>
    /// Session
    /// </summary>
    private ISession miSession;

    /// <summary>
    /// Session Factory
    /// </summary>
    private ISessionFactory miSessionFactory;
    private Configuration miConfiguration = new Configuration();
    private static readonly ILog log = LogManager.GetLogger(typeof(NHibernatePersistencia).Name);

    private static IRepositorio Repositorio;

    #endregion

    #region Constructor

    private NHibernatePersistencia()
    {
        //miConfiguration.Configure("hibernate.cfg.xml");
        try
        {
            miConfiguration.Configure();
            this.miSessionFactory = miConfiguration.BuildSessionFactory();
            this.miSession = this.SessionFactory.OpenSession();
            log.Debug("Se carga NHibernate");

        }
        catch (Exception ex)
        {
            log.Error("No se pudo cargar Nhibernate " + ex.Message);
            throw ex;
        }

    }

    public static IRepositorio Instancia
    {
        get
        {
            if (Repositorio == null)
            {
                Repositorio = new NHibernatePersistencia();
            }
            return Repositorio;
        }
    }

    #endregion

    #region Propiedades

    /// <summary>
    /// Sesion de NHibernate
    /// </summary>
    public ISession Session
    {
        get { return miSession.SessionFactory.GetCurrentSession(); }
    }

    /// <summary>
    /// Sesion de NHibernate
    /// </summary>
    public ISessionFactory SessionFactory
    {
        get { return this.miSessionFactory; }
    }

    #endregion

In wich way can i create a single instance for all services?

© Stack Overflow or respective owner

Related posts about web-services

Related posts about nhibernate