"Permanent" SessionFactory, ASP.NET MVC, and nHibernate

I am building an application with Fluent nHibernate / ASP.NET MVC - and I dug it out and realized that it was his best practice to open a "persistent" SessionFactory and then use sessions for each database query. Ok, that sounds good ...

I am completely confused about how to do this. All I find involves a whole structured structure that uses some kind of IoC container system ... and this is too advanced for what I still have. Are there even simpler examples of how to implement such a design?

I took a look at Where Can I Find Good NHibernate and ASP.NET MVC Reference Application

I even read the book ASP.NET MVC in Action, but this example is much more complicated than what I'm trying to achieve. I thought that the singleton model would work in Application_Start " global.asax", but this did not produce the results I was hoping for. He will continue to use my factory and never recreate it.

+3
source share
2 answers

You can highlight ISessionFactoryas singleton:

public sealed class FactoryManager
{
    private static readonly ISessionFactory _instance = CreateSessionFactory();

    static FactoryManager()
    { }

    public static ISessionFactory Instance
    {
        get { return _instance; }
    }

    private static ISessionFactory CreateSessionFactory()
    {
        // TODO: configure fluentnhibernate and create a session factory
    }
}

Now you can use FactoryManager.Instancein your code:

using (var session = FactoryManager.Instance.OpenSession())
using (var tx = session.BeginTransaction())
{
    // TODO: use the session here
    tx.Commit();
}
+5
source

GetSessionFactory MvcApplication. factory . .

, , , , , .

+2

Source: https://habr.com/ru/post/1778153/


All Articles