NHibernate & WCF: Performance (session reuse) vs. concurrency (simultaneous requests)

跟風遠走 提交于 2019-12-03 16:00:13

The easy answer: You don't re-use NHibernate sessions.

They're not heavyweight objects and they are designed to be created, manipulated and disposed following the Unit of Work pattern. Attempting to "share" these across multiple requests goes against their intended usage.

Fundamentally, the cost of synchronizing access to the sessions correctly will almost certainly negate any benefit you gain by recycling them to avoid re-initializing them. Let's also consider that these costs are a drop in the pond of the SQL you'll be executing.

Remember that NHibernate's Session Factory is the heavyweight object. It's thread-safe, so you can and should share a single instance across all requests out of the box.

Your code should look conceptually like this:

public class Service : IService
{
    static Service()
    {
        Configuration Cfg = new Configuration();
        Cfg.Configure();
        Cfg.AddAssembly("LegacyGate.Persistence");
        Service.SessionFactory = Cfg.BuildSessionFactory();
    }

    protected static ISessionFactory SessionFactory { get; private set; }

    public void ServiceMethod(...)
    {
        using(var session = Service.SessionFactory.CreateSession())
        {
            // Do database stuff
            ...
        }
    }
}

As an aside: Ideally, you'd be dependency-injecting the ISessionFactory into the service.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!