0

我有一个使用 nhibernate 的网络服务。我在存储库上有一个单例模式,但是在每次调用服务时,它都会创建一个非常昂贵的会话工厂的新实例。我能做些什么?

    #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

我可以通过哪种方式为所有服务创建单个实例?

4

1 回答 1

1

我想你已经提到了解决方案。您必须为 Sessionfactory-Provider 使用 Singleton。就我个人而言,我更喜欢使用 Spring 来管理我的 ApplicationContext 并连接我的对象,但您不必这样做。只需不要将 NHibernatePersistencia-Object 用作​​服务,而是用作 SessionProvider,就可以了。

您的服务可能如下所示:

public class YourService : IYourService
{
    public User GetUsers(int id)
    {
        using(NHibernatePersistencia.OpenSession())
        {
            return session.Load(typeof(user), id);
        }
    }      
}

...对于您的 SessionProvider,我建议您始终根据请求打开新会话。长期会议缓慢且不断增长。考虑到 Web 服务中有多个用户,这似乎不是一个好主意。

public class NHibernatePersistencia
{
    /* ...  */
    public ISession OpenSession()
    {
        return this.SessionFactory.OpenSession();
    }
    /* ...  */
}

这很简单,但应该可以。也许您想看看这个nhibernate.info 示例。那里的 NHibernateHelper 非常像您的 NHibernatePersistencia-Class。

于 2011-01-14T21:50:18.563 回答