Nhibernate IsessionFactory的Unity Xml配置

时间:2015-04-20 08:13:41

标签: c# nhibernate unity-container xml-configuration

我使用代码

解决了会话工厂问题
UnityContainer.RegisterInstance(typeof(ISessionFactory),
                new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory());

我的服务将属性定义为

public class myService
{
   [Dependency]
   public ISessionFactory SessionFactory{get;set;}
}

但是不知道如何使用unity 2的XML配置来配置它。

1 个答案:

答案 0 :(得分:0)

免责声明,此答案与此处讨论的内容https://stackoverflow.com/a/29730411/1679310(评论)更相关

让我为您提供与您的映射相关的更多详细信息。

首先,减少全名:

// here we have namespace, not needed below for classes, if is the same
<hibernate-mapping  ... namespace="NhibernateTesting.Models" >

对原始类映射进行了注释,我的方法是替换它:

// <class name="NhibernateTesting.Models.ProductList" table="ProductList" lazy="false">    
<class name="ProductList" table="ProductList" 
  lazy="true" // always use LAZY
  batch-size="25" // optimization for loading - avoid 1 + N
>

//<id name="Id">
//  <generator class="native" />
//</id>
// more readable version
<id name="Id" generator="native" />

// these are OK
<property name="Name" />
<property name="Owner" />

// collection should be ALWAYS lazy
// <bag name="Viewers" table="ProductListViewer" lazy="false">
// and also, optimization as batch size is needed
<bag name="Viewers" table="ProductListViewer" 
  lazy="true" // LAZY is must, 
  batch-size="25" cool optimization to avoid 1 + N
>
  <key column="ProductListId" />
  <element column="Username" type="System.String"/>
</bag>

// I would never use MANY-TO-MANY
// <bag name="Products" table="ProductListProductXRef" lazy="false" cascade="all" fetch="select">
<bag name="Products" table="ProductListProductXRef" 
   inverse="true" // in many to many only one side could be inverse
   lazy="true" 
   cascade="none"  // cascade here means, delete PRODUCTS
                  // not the pairing table, so I would expect that we need none
   fetch="select">
  <key column="ProductListId" />

  // I would avoid many to many if possible
  <many-to-many column="ProductId" class="NhibernateTesting.Models.Product" />
 ...

检查这些链接以获取更多详细信息。

懒惰

批量提取

避免多对多

何时使用级联

这些将是我的建议,适用于所有映射。

一般来说,这应该是类映射

<class 
  name="ProductList" 
  table="ProductList" 
  lazy="true"
  batch-size="25"
>

如果我们需要版本控制:

<class 
  name="ProductList" 
  table="ProductList" 
  lazy="true"
  batch-size="25"
  optimistic-lock="version" 
  dynamic-update="true" 
>

<version name="Timestamp" generated="always" unsaved-value="null" type="BinaryBlob">
  <column name="RowVersion" not-null="false" sql-type="timestamp"/>
</version>

这应该是集合映射:

<bag name="Items" 
   lazy="true" 
   inverse="true" 
   batch-size="25" 
   cascade="all-delete-orphan">
  <key column="Item_ID" />
  <one-to-many class="SomeItemClass"/>
</bag>