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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With