本文介绍了NETiber DI处理的NHibernate SessionFactory的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图将NHibernate SessionFactory设为单例,将Session设为范围,所有这些都由.NET Core依赖项注入处理.我在Startup.cs中配置了这些代码:

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()
);

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

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

推荐答案

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

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(...);
    }
}

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

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

这篇关于NETiber DI处理的NHibernate SessionFactory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 06:41