Dependency Injection with NHibernate Event Listeners

293 views
Skip to first unread message

Sammi Sinno

unread,
Jan 16, 2017, 7:43:36 PM1/16/17
to nhusers
I'm trying to do simple constructor injection with NHibernate Event Listners, here is an example:

        public class FormGeneratorUpdate : IPostUpdateEventListener
   
{
       
private readonly IHostingEnvironment _env;


       
public FormGeneratorUpdate(IHostingEnvironment env)
       
{
            _env
= env;
       
}


       
public void OnPostUpdate(PostUpdateEvent @event)
       
{
           
string typeName = @event.Entity.GetType().Name;
           
dynamic entity = @event.Entity;
           
string filePath =
                $
"{_env.ContentRootPath}\\App_Data\\FormGenerator\\{typeName}\\{entity.Id}.json";


           
File.Delete(filePath);


           
string json = JsonConvert.SerializeObject(entity);
           
using (FileStream fs = File.Create(filePath))
           
{
               
// Add some text to file
               
Byte[] content = new UTF8Encoding(true).GetBytes(json);
                fs
.Write(content, 0, content.Length);
           
}
       
}
   
}


I currently set up the NHibernate bytecodeProvider to the autofac implementation like so: 

        NHibernate.Cfg.Environment.BytecodeProvider =
               
new AutofacBytecodeProvider(_container, new ProxyFactoryFactory(), new DefaultCollectionTypeFactory());

This seems to work just fine when building the session factory, but the question I have is how do I register an event listener with an NHibernate configuration without first instantiating it? Every way I can register it requires me to first instantiate the object like so:

    cfg.SetListener(ListenerType.Update, new FormGeneratorUpdate());


Since the constructor is not empty it is throwing an error... I've tried just registering the event listeners with Autofac and not setting them on the configuration and that doesn't seem to work either, I believe I have to set it on the configuration as well some how.

Sammi Sinno

unread,
Jan 17, 2017, 9:18:46 AM1/17/17
to nhusers
So figured this out, I was able to get DI working with a default constructor and registering the events with .AsSelf() instead of .AsImplementedInterfaces()
Reply all
Reply to author
Forward
0 new messages