如何在配置中引用Spring.Net的ObjectFactory?

时间:2009-06-21 11:49:21

标签: prototype spring spring.net objectfactory

我想使用原型拦截器而不是单例拦截器,因此每个会话都会获得一个新的拦截器实例。

我查看了HibernateTransactionManager类,我认为“EntityInterceptorObjectName”和“ObjectFactory”是我必须设置的属性。

虽然EntityInterceptorObjectName非常明显,但我不知道如何引用ObjectFactory ,当它是“ObjectFactories的母亲”时,例如创建AppContext / HibernateTransactionManager的相同ObjectFactory。

配置的相关部分:

   <object id="HibernateTransactionManager" type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate20">
    <property name="DbProvider" ref="DbProvider"/>
    <property name="SessionFactory" ref="SessionFactory"/>
    <!-- the name of my non-Singleton EntityInterceptor-->
     <property name="EntityInterceptorObjectName" value="MyPrototypeEntityInterceptor" />
    <!-- What should I put as ref here? -->
    <property name="ObjectFactory" ref="" />
  </object>

  <object id="MyPrototypeEntityInterceptor" type="Hib.EntityInterceptor, Hib.Interceptors" singleton="false">
  </object>  

1 个答案:

答案 0 :(得分:1)

据我所知,您可以使用自己的IObjectFactory实现,根据给定的名称创建所需的对象。如果您希望能够使用Spring-ApplicationContext中定义的对象,您还可以实现IObjectFactoryAware以将ObjectFactory连接到Spring IoC容器。

这可以让你做任何你想做的事。创建任何类的新实例,并使用IoC容器中的对象填充其属性(例如SessionFactory,...)。

public class MyObjectFactoryAware : IObjectFactoryAware, IObjectFactory
{
   //this property will be set by the IoC container
   ObjectFactory {get; set;}

   //IObjectFactory implementation
   virtual object GetObject(string objectName)
   {
      MyEntityInterceptor interceptor = new MyEntityInterceptor();
      interceptor.SessionFactory = this.ObjectFactory.getObject("SessionFactory");
      return interceptor;

      //or of course if you just need it for wireing simply:
      //return this.ObjectFactory.getObject(objectName);
   }   
}

和映射:

<object id="HibernateTransactionManager" type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate20">
  <property name="DbProvider" ref="DbProvider"/>
  <property name="SessionFactory" ref="SessionFactory"/>
  <!-- the name of my non-Singleton EntityInterceptor-->
  <property name="EntityInterceptorObjectName" value="MyPrototypeEntityInterceptor" />
  <!-- and the name of the objectFactory -->
  <property name="ObjectFactory" ref="MyObjectFactory" />
</object>

<object id="MyObjectFactory" type="Hib.MyObjectFactoryAware, Hib.Interceptors">
</object>

<object id="MyPrototypeEntityInterceptor" type="Hib.EntityInterceptor, Hib.Interceptors" singleton="false">
</object>