开发者

Ninject / NHibernate Events + Observer Pattern

开发者 https://www.devze.com 2023-01-01 15:41 出处:网络
I am trying to implement an observer pattern using ninject and NHibernate. I\'d like to be able to inject observers that act as \"triggers\" when an object is persisted or deleted via NHibernate.

I am trying to implement an observer pattern using ninject and NHibernate.

I'd like to be able to inject observers that act as "triggers" when an object is persisted or deleted via NHibernate.

Key points-

  1. I want the obse开发者_Python百科rver to be notified any time an object is persisted, including cascaded saves, which is why I am using NHibernate PostInsert/PostUpdate events.
  2. I want to be able to inject the observers via Ninject (don't want the kernel anywhere in the nhibernate event handlers).
  3. The observers are different depending on the type of the object being persisted, so I need a good way to know which observers should be called in the NHibernate events.

My code works great now for objects that are loaded via NHibernate using constructor injection. An observer class is injected into the domain model, which is carried through the nhibernate events and can be fired off no problem.

The problem: Our existing codebase uses default constructors for our domain objects versus a factory. Because of this, the observers will not be injected unless we switch to using a factory.

I know that switching everything to a factory will work, but I wanted to see if anyone has any better suggestions for accomplishing this. So, should I make a factory to instantiate new objects or something else?


It looks like you are making life complicated for yourself by trying to put Observer pattern on top of NHibernate's Event Handler pattern.

NHibernate already provides a way of having pluggable event listeners - why not just make use of that?

class FooPostInsertEventListener : IPostInsertEventListener
{
    public void OnPostInsert(PostInsertEvent @event)
    {
        var entity = @event.Entity;
        var entityType = entity.GetType();

        if (entityType != typeof(Foo)) return;

        ProcessFoo(entity);
    }
}

If you are desperate to go through the Kernel, then you can even use the Kernel when configuring NHibernate. Something like this:

config.EventListeners.PostInsertEventListeners = Kernel.GetAll<IPostInsertEventListener>().ToArray();
0

精彩评论

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