gpt4 book ai didi

c# - 在 WCF 服务中使用语句

转载 作者:太空宇宙 更新时间:2023-11-03 13:37:17 25 4
gpt4 key购买 nike

我正在使用 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 方法的调用)时,它工作正常。

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

谢谢,暗里

最佳答案

你需要的是Session的生命周期,它会和WCF Service的请求有关。这就是您应该用谷歌搜索的内容。

这里有一些链接,如何:

请求持久 session :

关于c# - 在 WCF 服务中使用语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18287622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com