NETiber DI处理的NHibernate SessionFactory

Bar*_*llz 6 c# nhibernate asp.net-core

试图将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()
);
Run Code Online (Sandbox Code Playgroud)

我的问题是-例如,如何在存储库类中准确传递Session或SessionFactory实例?

小智 6

只需将ISession对象作为参数传递给存储库构造函数。

public class Repository {
    private readonly ISession session;

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

    public void DoSomething() {
        this.session.SaveOrUpdate(...);
    }
}
Run Code Online (Sandbox Code Playgroud)

当您从ServicesCollection(DI)请求存储库实例时,将自动解析ISession。