Unity IoC容器中的nHibernate注册 - ISession vs ISessionFactory

时间:2017-12-01 06:32:16

标签: nhibernate fluent-nhibernate unity-container

在我的IoC容器(Unity)中注册nHibernate的正确方法是什么?

我觉得我应该将ISessionFactory注入我的构造函数中,而不是ISession,因为我想创建&自己摧毁会议。

目前我有这个:

public static void RegisterTypes(IUnityContainer container)
{
    container
        .RegisterType<ISessionFactory>(
            new ContainerControlledLifetimeManager(),
            new InjectionFactory(c =>
            {
                return Fluently.Configure().Database(MsSqlConfiguration.MsSql2012.ConnectionString(connStr => connStr.FromConnectionStringWithKey("db")))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<CategoryMap>())
                .BuildConfiguration()
                .BuildSessionFactory();
            })
    );
}

并使用它:

public class SomeClass
{
    private readonly ISessionFactory sessionFactory;

    public SomeClass(ISessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }

    public void DoSomething()
    {
        using (ISession session = this.sessionFactory.OpenSession())
        {
            using (ITransaction transaction = session.BeginTransaction())
            {
                // Something here ...
                session.Save(...);
                transaction.Commit();
            }
        }
    }
}

我应该通过ISession而不是'是' - 为什么? ISessionISessionFactory的正确生命周期政策是什么?

0 个答案:

没有答案