2

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 メソッドの呼び出し) を削除すると、正常に動作します。

私の質問はなぜですか?これを正しく実装するにはどうすればよいですか?

ありがとう、オムリ

4

1 に答える 1

1

必要なのは、WCF サービスの要求に関連するセッションの有効期間です。そして、これはあなたがググるべきものです。

ここにいくつかのリンクがあります。

リクエスト持続セッション:

于 2013-08-17T11:17:38.023 に答える