在WCF服务中使用语句

时间:2013-08-17 10:14:19

标签: c# wcf nhibernate

我正在使用NHibernate连接到我的数据库,并按如下方式检索一些数据:

public abstract class BaseContext<TContext> : IBaseContext<TContext> where TContext : IGuid
{
    #region Data Members

    // NHibernate session
    private readonly Lazy<ISession> _session;

    // Logger
    private static readonly ILog log = LogManager.GetLogger(typeof(BaseContext<TContext>));

    #endregion

    #region Ctor

    protected BaseContext()
    {

        // Initialize session 
        _session = new Lazy<ISession>(NHibernateHelper.OpenSession);
        // log
        log.Debug("Session has been created but has not yet been used.");
    }

    #endregion

    #region Propreties

    /// <summary>
    /// Lazy load a session with NHibernate
    /// </summary>
    public ISession Session
    {
        get { return _session.Value; }
    }

    #endregion

    #region Methods

    /// <summary>
    /// Retreives all object of type <see cref="TContext"/> from the database.
    /// </summary>
    /// <returns>A list of all the <see cref="TContext"/> items</returns>
    public IEnumerable<TContext> Get()
    {
        try
        {
            log.DebugFormat("Retrieving all items of type {0} from the database.",
                    typeof(TContext).Name);

            // Return all the items of TContext type
            return from item in Session.Query<TContext>()
                   select item;
        }
        catch (Exception ex)
        {
            log.Error("Could not retreive items from the database.", ex);
            return default(IEnumerable<TContext>); 
        }
    }

    /// <summary>
    /// Disposes the context
    /// </summary>
    public void Dispose()
    {
        // Dispose session
        Session.Dispose();
    }

    #endregion
}

我有一个包装类,代表我想要检索的每个实体,例如:

public class EntityContext : BaseContext<DataEntity>
{
    #region Methods

    /// <summary>
    /// Gets a list of all enitities
    /// </summary>
    /// <returns>A list of all entities</returns>
    public new IEnumerable<DataEntity> Get()
    {
        return base.Get();
    }

    #endregion
}

为了公开这个,我创建了一个使用它的WCF服务:

    public List<DataEntity> Get()
    {
        using (EntityContext context = new EntityContext())
        {
            var entities = context.Get();
            return entities.ToList();
        }
    }

当我使用WCF服务时,我一直收到“连接中止”异常,直到我找出原因。当我删除using语句(调用Dispose方法)时,它可以正常工作。

我的问题是为什么?我该如何正确实现?

谢谢, 欧米

1 个答案:

答案 0 :(得分:1)

您需要的是会话生存期,它将与WCF服务的请求相关。这就是你应该谷歌的。

以下是一些链接,如何:

请求持续会话: