C# 在WCF服务中使用语句
我正在使用NHibernate连接到我的数据库并检索一些数据,如下所示:C# 在WCF服务中使用语句,c#,wcf,nhibernate,C#,Wcf,Nhibernate,我正在使用NHibernate连接到我的数据库并检索一些数据,如下所示: public abstract class BaseContext<TContext> : IBaseContext<TContext> where TContext : IGuid { #region Data Members // NHibernate session private readonly Lazy<ISession> _session;
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方法时,它工作正常
我的问题是为什么?我应该如何正确地实现这一点
谢谢,
Omri您需要的是会话生存期,它将与WCF服务的请求相关。这就是你应该用谷歌搜索的原因 以下是一些链接,介绍如何: 请求本届会议: -NHibernate文档:NHibernate.Context.wcfoOperationSessionContext -示例
如果您返回实体,我可以看到这个问题是如何发生的;。但是,您确定即使返回实体也存在此问题吗@ErenErsönmez是的,这正是我所不理解的……ToList只会强制加载根实体,但不会加载它们的惰性属性。当第一次访问延迟加载时,这些将在稍后加载。此时会话已被释放。。。不懒惰。这就是为什么你需要一个持久的请求session@RadimKöhler您是对的,我制作了所有映射,而不是惰性加载,只是为了检查它是否有效,它确实有效。所以现在我的问题是,如何创建一个“持续请求”会话?你答案中的例子使用了我不想使用的IOC容器。你有没有一个没有的例子?你是对的。。。我已经用一些链接扩展了答案。国际奥委会是你无论如何都应该开始考虑的事情;但是,wcfoOperationSessionContext是现成的!