问题描述
我开始构建应用程序,并且打算使用ServiceStack.只想知道什么是处理NHibernate ISession或其他按请求"上下文特定的会话对象的最佳实践/好的方法.
I am starting to build an app, and I'm planning to use ServiceStack. Just want to know what are the best practices/good approaches for handling NHibernate ISession or, other "per request" context specific session objects.
我想像在Ioc中注册一个ISessionFactory:
I thought registering a ISessionFactory in the Ioc like:
container.Register<ISessionFactory>(sessionFactory);
然后在需要时获得一个新的Session对象...或者直接提供该session对象:
And when needed get a new Session object... Or maybe provide the session object directly:
container.Register<ISession>(c => sessionFactory.OpenSession()).ReusedWithin(ReuseScope.None);
或者通过Global.asax BeginRequest事件处理ISession和默认事务:
Or either handle the ISession and a default transaction via the Global.asax BeginRequest event:
protected void Application_BeginRequest(object sender, EventArgs e)
{
var session = factory.OpenSession();
ITransaction itrans = session.BeginTransaction();
Context.Items.Add("session", session);
Context.Items.Add("trans", itrans);
}
因此,我有点迷失了,鉴于上述技术或类似技术(如EF或其他Rest-Services框架),最佳实践是什么?
So, I am kind of lost, what are the best practices, given the above technologies, or similar ones, like EF or another Rest-Services framework?
预先感谢
推荐答案
有关如何最佳地一起使用ServiceStack和NHibernate的完整示例,请参见此博客文章:
See this blog post for a complete example of how to optimally use ServiceStack and NHibernate together:
http://www.philliphaydon.com/2012/06 /using-nhibernate-with-servicestack/这是上面的帖子中使用的AppHost示例:
http://www.philliphaydon.com/2012/06/using-nhibernate-with-servicestack/Here's the AppHost example used in the above post:
public class Global : HttpApplication
{
public class SampleServiceAppHost : AppHostBase
{
private readonly IContainerAdapter _containerAdapter;
public SampleServiceAppHost(ISessionFactory sessionFactory)
: base("Service Stack with Fluent NHibernate Sample", typeof(ProductFindService).Assembly)
{
base.Container.Register<ISessionFactory>(sessionFactory);
}
public override void Configure(Funq.Container container)
{
container.Adapter = _containerAdapter;
}
}
void Application_Start(object sender, EventArgs e)
{
var factory = new SessionFactoryManager().CreateSessionFactory();
(new SampleServiceAppHost(factory)).Init();
}
}
这篇关于每个请求的ServiceStack NHibernate会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!