开发者

Is it possible to use a factory method to create instances of your class using fluent nhibernate?

开发者 https://www.devze.com 2023-02-05 14:36 出处:网络
For example, I have a set of domain classes. Those classes implement a common interface. The interface is public but the classes themselves are internal. Insta开发者_高级运维nces of those classes can

For example, I have a set of domain classes. Those classes implement a common interface. The interface is public but the classes themselves are internal. Insta开发者_高级运维nces of those classes can be created by using a provided factory that is public. Furthermore, each class instance is persisted using a one-table-per-hierarchy technique.

How can Fluent NHibernate be used is this case? Any help would be greatly appreciated.

Thanks, Blake


This is more NHibernate specific than FNH, but you have two options as far as I can see.

  1. Implement IInterceptor.Instantiate(string entityName, EntityMode entityMode, object id) - you would also have to associate said interceptor with any NHibernate sessions you start.

  2. As per http://fabiomaulo.blogspot.com/2008/11/entities-behavior-injection.html , subclass ReflectionOptimizer' and implement theCreateInstance()` method (need one for each type you want to build a factory for). There is some configuration and wiring I don't fully understand, and I suspect this is basically an overkill version of method #1.

If you are wanting to inject persisted fields and properties for your domain class, I'm not sure if there is a way to do that as it is a rather non-trivial matter to generalise.


You can also take advantage of the event system in NHibernate 2.0+. The Load event allows you to create the object for NHibernate, as well. All you have to do is create an implementation of ILoadEventListener, add it to the event listeners for the ISessionFactory or ISession, and profit!

 using NHibernate.Event.Default

 public class MyCreatorListener : DefaultLoadEventListener
 {
   // this is the single method defined by the LoadEventListener interface
   public override void OnLoad(LoadEvent theEvent, LoadType loadType)
   {
     if(null == theEvent.InstanceToLoad) // Not null if user supplied object
     {
       theEvent.InstanceToLoad = MyFactory.Create(loadType); // Or whatever.
     }
   }
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消