Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate SessionFactory handled by .NET Core DI

Trying to make the NHibernate SessionFactory as a singleton and Session as scoped, all this handled by the .NET Core dependency injection. I configured those in the Startup.cs as such:

services.AddSingleton<NHibernate.ISessionFactory>(factory =>
{
    return Fluently
                .Configure()
                .Database(() =>
                {

                    return FluentNHibernate.Cfg.Db.MsSqlConfiguration
                            .MsSql2012
                            .ShowSql()
                            .ConnectionString(ConnectionString);
                })
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Model>())
                .BuildSessionFactory();
}); 

services.AddScoped<NHibernate.ISession>(factory =>
   factory
        .GetServices<NHibernate.ISessionFactory>()
        .First()
        .OpenSession()
);

My question is - how do I exactly pass the Session or the SessionFactory instance, for instance, in a repository class?

like image 318
Barrett_killz Avatar asked Dec 10 '17 20:12

Barrett_killz


People also ask

Does NHibernate work with .NET core?

NHibernate is the ORM, an object-relational platform that works on the ASP.Net core. Therefore, we can easily deploy the core project developed in ASP.NET that uses NHibernate on the Linux server without any effort. The application works in the same way as it will do on a windows platform.

What is NHibernate in .NET core?

NHibernate is a mature, open source object-relational mapper for the . NET framework. It's actively developed, fully featured and used in thousands of successful projects.

What is Session factory in NHibernate?

Abstract factory pattern: SessionFactory Interface. The NHibernate framework uses the abstract factory pattern for creating sessions and using them to persist the objects into the database. It is a factory class that is used in an aspx page to create session objects.


1 Answers

Just pass the ISession object as a parameter to the repository constructor.

public class Repository {
    private readonly ISession session;

    public Repository(NHibernate.ISession session) {
        this.session = session;
    }

    public void DoSomething() {
        this.session.SaveOrUpdate(...);
    }
}

When you ask for a Repository-instance from the ServicesCollection (DI), the ISession will be resolved automatically.

like image 150
Sircuri Avatar answered Sep 23 '22 05:09

Sircuri