尝试将NHibernate SessionFactory设为单例,将Session设置为范围,所有这些都由.NET Core依赖注入处理。我在Startup.cs中配置了这些:
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()
);
我的问题是 - 如何在一个存储库类中完全传递Session或SessionFactory实例?
答案 0 :(得分:5)
只需将ISession对象作为参数传递给存储库构造函数。
public class Repository {
private readonly ISession session;
public Repository(NHibernate.ISession session) {
this.session = session;
}
public void DoSomething() {
this.session.SaveOrUpdate(...);
}
}
当您从ServicesCollection(DI)请求Repository-instance时,ISession将自动解决。