title: NInject, nHibernate, and auditing in ASP.NET MVC
body: <p>I am working on an inherited application which makes use of NInject and nHibernate as part of an ASP.NET MVC (C#) application. Currently, I'm looking at a problem with the auditing of modifications. Each entity has ChangedOn/ChangedBy and CreatedOn/CreatedBy fields, which are mapped to database columns. However, these either get filled with the wrong username or no username at all. I think this is because it has been configured in the wrong way, but I don't know enough about nHibernate and NInject to solve the issue, so I hope someone can help. Below some code snippets to hopefully provide sufficient insight in the application.</p>
  
  <p><strong>Creating the session factory and session:</strong></p>
  
  <pre><code>public class NHibernateModule : NinjectModule
  {
      public override void Load()
      {
          Bind&lt;ISessionFactory&gt;().ToProvider(new SessionFactoryProvider()).InSingletonScope();
  
          Bind&lt;ISession&gt;().ToProvider(new SessionProvider()).InRequestScope();
          Bind&lt;INHibernateUnitOfWork&gt;().To&lt;NHibernateUnitOfWork&gt;().InRequestScope();
          Bind&lt;User&gt;().ToProvider(new UserProvider()).InRequestScope();
          Bind&lt;IStamper&gt;().ToProvider(new StamperProvider()).InRequestScope();
      }
  }
  
  public class SessionProvider : Provider&lt;ISession&gt;
  {
      protected override ISession CreateInstance(IContext context)
      {
          // Create session
          var sessionFactory = context.Kernel.Get&lt;ISessionFactory&gt;();            
          var session = sessionFactory.OpenSession();            
          session.FlushMode = FlushMode.Commit;
  
          return session;
      }
  }
  
  public class SessionFactoryProvider : Provider&lt;ISessionFactory&gt;
  {
      protected override ISessionFactory CreateInstance(IContext context)
      {
          var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ToString();
          var stamper = context.Kernel.Get&lt;IStamper&gt;();
  
          return NHibernateHelper.CreateSessionFactory(connectionString, stamper);
      }
  }
  
  public class StamperProvider : Provider&lt;IStamper&gt;
  {
      protected override IStamper CreateInstance(IContext context)
      {
          System.Security.Principal.IPrincipal user = HttpContext.Current.User;
          System.Security.Principal.IIdentity identity = user == null ? null : user.Identity;
          string name = identity == null ? "Unknown" : identity.Name;
  
          return new Stamper(name);
      }
  }
  
  public class UserProvider : Provider&lt;User&gt;
  {
      protected override UserCreateInstance(IContext context)
      {
          var userRepos = context.Kernel.Get&lt;IUserRepository&gt;();
  
          System.Security.Principal.IPrincipal user = HttpContext.Current.User;
          System.Security.Principal.IIdentity identity = user == null ? null : user.Identity;
          string name = identity == null ? "" : identity.Name;
  
          var user = userRepos.GetByName(name);
          return user;
      }
  }
  </code></pre>
  
  <p><strong>Configuring the session factory:</strong></p>
  
  <pre><code>public static ISessionFactory CreateSessionFactory(string connectionString, IStamper stamper)
      {
          // Info: http://wiki.fluentnhibernate.org/Fluent_configuration
          return Fluently.Configure()
                  .Database(MsSqlConfiguration.MsSql2008
                      .ConnectionString(connectionString))
                  .Mappings(m =&gt; 
                      {
                          m.FluentMappings
                              .Conventions.Add(PrimaryKey.Name.Is(x =&gt; "Id"))
                              .AddFromAssemblyOf&lt;NHibernateHelper&gt;();
  
                          m.HbmMappings.AddFromAssemblyOf&lt;NHibernateHelper&gt;();
                      })
                  // Register 
                  .ExposeConfiguration(c =&gt; {
                      c.EventListeners.PreInsertEventListeners = 
                          new IPreInsertEventListener[] { new EventListener(stamper) };
                      c.EventListeners.PreUpdateEventListeners =
                          new IPreUpdateEventListener[] { new EventListener(stamper) };
                  })
                  .BuildSessionFactory();
       }
  </code></pre>
  
  <p><strong>Snippet from the eventlistener:</strong></p>
  
  <pre><code>public bool OnPreInsert(PreInsertEvent e)
  {
      _stamper.Insert(e.Entity as IStampedEntity, e.State, e.Persister);
      return false;
  }
  </code></pre>
  
  <p>As you can see the session factory is in a singleton scope. Therefore the eventlistener and stamper also get instantiated in this scope (I think). And this means that when the user is not yet logged in, the username in the stamper is set to an empty string or "Unknown".
  I tried to compensate for this problem, by modifying the Stamper. It checks if the username is null or empty. If this is true, it tries to find the active user, and fill the username-property with that user's name:</p>
  
  <pre><code>    private string GetUserName()
      {
          if (string.IsNullOrWhiteSpace(_userName))
          {
              var user = ServiceLocator.Resolve&lt;User&gt;();
  
              if (user != null)
              {
                  _userName = user.UserName;
              }
          }
  
          return _userName;
      }
  </code></pre>
  
  <p>But this results in a completely different user's name, which is also logged in to the application, being logged in the database. My guess this is because it resolves the wrong active user, being the last user logged in, instead of the user that started the transaction.</p>