Add NHibernate with .net core - Add auditing through HttpContext











up vote
0
down vote

favorite












I am in dire need of your help. I have migrated some legacy .Net web API applications to .net core and get it all working except the Envers piece of it. The major problem I am facing is to pass user name to the RevisionListener. As RevisionListener does not support DI I am not able to inject HttpContextAccessor to get the context. Alternatively if I use static HttpContextAccessor I am running with same context from two different request.



Even if I use "IHttpContextAccessor " due t static nature of the class Revision table is holding the same context between two requests from 2 different users.



Any example will be appreciated!



Here is the code I am using to configure nHibernate



// NHibernateExtension method to onboard nhiberbate to .net core
public static class NHibernateExtension



{
public static void AddNhibernate(this IServiceCollection services, string connectionString,string schemaName )

{



services.AddSingleton((provider) =>

{

var cfg = new NHibernate.Cfg.Configuration();

cfg.Configure("hibernate.cfg.xml");

cfg.SetProperty("connection.connection_string", connectionString);

cfg.AddProperties(new Dictionary<string, string>

{

{ NHibernate.Cfg.Environment.DefaultSchema, schemaName }

});

cfg.AddMapping(NHibernateConfig.GetMappings());



var enversConfiguration = GetEnversConfiguration();

cfg.SetEnversProperty(ConfigurationKey.DefaultSchema, "Audit");

cfg.IntegrateWithEnvers(enversConfiguration);





return cfg;

});



services.AddSingleton((provider) => provider.GetService<NHibernate.Cfg.Configuration>().BuildSessionFactory());



services.AddScoped((provider) => provider.GetService<ISessionFactory>().OpenSession());

}





private static FluentConfiguration GetEnversConfiguration()

{

var enversConf = new FluentConfiguration();



var userId = HttpContext.Current?.Request?.Headers["user_name"];

var userName = HttpContext.Current?.Request?.Headers["name"];



RevisionListener rn = new RevisionListener(userName, userId);

enversConf.SetRevisionEntity<RevisionDetails>(x => x.Id, x => x.RevisionTimestamp, rn);

enversConf.Audit<PrinterMapping>().SetTableInfo(x => x.Value = typeof(PrinterMapping).Name);

enversConf.Audit<Label>().SetTableInfo(x => x.Value = typeof(Label).Name);

enversConf.Audit<Language>().SetTableInfo(x => x.Value = typeof(Language).Name);

enversConf.Audit<Translation>().SetTableInfo(x => x.Value = typeof(Translation).Name);

return enversConf;

}



}


//this provides HttpContext through IHttpContextAccessor



public static class HttpContext



{

private static IHttpContextAccessor _contextAccessor;



public static Microsoft.AspNetCore.Http.HttpContext Current => _contextAccessor.HttpContext;



internal static void Configure(IHttpContextAccessor contextAccessor)

{

_contextAccessor = contextAccessor;

}

}


*/Listener****/



public class RevisionListener : IRevisionListener {



private string _userName = string.Empty;
private string _userId = string.Empty;

public RevisionListener(string userName, string userId)
: base()
{
this._userName = userName;
this._userId = userId;
}

public void NewRevision(object revisionEntity)
{
var casted = revisionEntity as RevisionDetails;

if (casted != null)
{
casted.UserName = this._userName;
casted.UserId = this._userId;
}
}


}










share|improve this question


























    up vote
    0
    down vote

    favorite












    I am in dire need of your help. I have migrated some legacy .Net web API applications to .net core and get it all working except the Envers piece of it. The major problem I am facing is to pass user name to the RevisionListener. As RevisionListener does not support DI I am not able to inject HttpContextAccessor to get the context. Alternatively if I use static HttpContextAccessor I am running with same context from two different request.



    Even if I use "IHttpContextAccessor " due t static nature of the class Revision table is holding the same context between two requests from 2 different users.



    Any example will be appreciated!



    Here is the code I am using to configure nHibernate



    // NHibernateExtension method to onboard nhiberbate to .net core
    public static class NHibernateExtension



    {
    public static void AddNhibernate(this IServiceCollection services, string connectionString,string schemaName )

    {



    services.AddSingleton((provider) =>

    {

    var cfg = new NHibernate.Cfg.Configuration();

    cfg.Configure("hibernate.cfg.xml");

    cfg.SetProperty("connection.connection_string", connectionString);

    cfg.AddProperties(new Dictionary<string, string>

    {

    { NHibernate.Cfg.Environment.DefaultSchema, schemaName }

    });

    cfg.AddMapping(NHibernateConfig.GetMappings());



    var enversConfiguration = GetEnversConfiguration();

    cfg.SetEnversProperty(ConfigurationKey.DefaultSchema, "Audit");

    cfg.IntegrateWithEnvers(enversConfiguration);





    return cfg;

    });



    services.AddSingleton((provider) => provider.GetService<NHibernate.Cfg.Configuration>().BuildSessionFactory());



    services.AddScoped((provider) => provider.GetService<ISessionFactory>().OpenSession());

    }





    private static FluentConfiguration GetEnversConfiguration()

    {

    var enversConf = new FluentConfiguration();



    var userId = HttpContext.Current?.Request?.Headers["user_name"];

    var userName = HttpContext.Current?.Request?.Headers["name"];



    RevisionListener rn = new RevisionListener(userName, userId);

    enversConf.SetRevisionEntity<RevisionDetails>(x => x.Id, x => x.RevisionTimestamp, rn);

    enversConf.Audit<PrinterMapping>().SetTableInfo(x => x.Value = typeof(PrinterMapping).Name);

    enversConf.Audit<Label>().SetTableInfo(x => x.Value = typeof(Label).Name);

    enversConf.Audit<Language>().SetTableInfo(x => x.Value = typeof(Language).Name);

    enversConf.Audit<Translation>().SetTableInfo(x => x.Value = typeof(Translation).Name);

    return enversConf;

    }



    }


    //this provides HttpContext through IHttpContextAccessor



    public static class HttpContext



    {

    private static IHttpContextAccessor _contextAccessor;



    public static Microsoft.AspNetCore.Http.HttpContext Current => _contextAccessor.HttpContext;



    internal static void Configure(IHttpContextAccessor contextAccessor)

    {

    _contextAccessor = contextAccessor;

    }

    }


    */Listener****/



    public class RevisionListener : IRevisionListener {



    private string _userName = string.Empty;
    private string _userId = string.Empty;

    public RevisionListener(string userName, string userId)
    : base()
    {
    this._userName = userName;
    this._userId = userId;
    }

    public void NewRevision(object revisionEntity)
    {
    var casted = revisionEntity as RevisionDetails;

    if (casted != null)
    {
    casted.UserName = this._userName;
    casted.UserId = this._userId;
    }
    }


    }










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I am in dire need of your help. I have migrated some legacy .Net web API applications to .net core and get it all working except the Envers piece of it. The major problem I am facing is to pass user name to the RevisionListener. As RevisionListener does not support DI I am not able to inject HttpContextAccessor to get the context. Alternatively if I use static HttpContextAccessor I am running with same context from two different request.



      Even if I use "IHttpContextAccessor " due t static nature of the class Revision table is holding the same context between two requests from 2 different users.



      Any example will be appreciated!



      Here is the code I am using to configure nHibernate



      // NHibernateExtension method to onboard nhiberbate to .net core
      public static class NHibernateExtension



      {
      public static void AddNhibernate(this IServiceCollection services, string connectionString,string schemaName )

      {



      services.AddSingleton((provider) =>

      {

      var cfg = new NHibernate.Cfg.Configuration();

      cfg.Configure("hibernate.cfg.xml");

      cfg.SetProperty("connection.connection_string", connectionString);

      cfg.AddProperties(new Dictionary<string, string>

      {

      { NHibernate.Cfg.Environment.DefaultSchema, schemaName }

      });

      cfg.AddMapping(NHibernateConfig.GetMappings());



      var enversConfiguration = GetEnversConfiguration();

      cfg.SetEnversProperty(ConfigurationKey.DefaultSchema, "Audit");

      cfg.IntegrateWithEnvers(enversConfiguration);





      return cfg;

      });



      services.AddSingleton((provider) => provider.GetService<NHibernate.Cfg.Configuration>().BuildSessionFactory());



      services.AddScoped((provider) => provider.GetService<ISessionFactory>().OpenSession());

      }





      private static FluentConfiguration GetEnversConfiguration()

      {

      var enversConf = new FluentConfiguration();



      var userId = HttpContext.Current?.Request?.Headers["user_name"];

      var userName = HttpContext.Current?.Request?.Headers["name"];



      RevisionListener rn = new RevisionListener(userName, userId);

      enversConf.SetRevisionEntity<RevisionDetails>(x => x.Id, x => x.RevisionTimestamp, rn);

      enversConf.Audit<PrinterMapping>().SetTableInfo(x => x.Value = typeof(PrinterMapping).Name);

      enversConf.Audit<Label>().SetTableInfo(x => x.Value = typeof(Label).Name);

      enversConf.Audit<Language>().SetTableInfo(x => x.Value = typeof(Language).Name);

      enversConf.Audit<Translation>().SetTableInfo(x => x.Value = typeof(Translation).Name);

      return enversConf;

      }



      }


      //this provides HttpContext through IHttpContextAccessor



      public static class HttpContext



      {

      private static IHttpContextAccessor _contextAccessor;



      public static Microsoft.AspNetCore.Http.HttpContext Current => _contextAccessor.HttpContext;



      internal static void Configure(IHttpContextAccessor contextAccessor)

      {

      _contextAccessor = contextAccessor;

      }

      }


      */Listener****/



      public class RevisionListener : IRevisionListener {



      private string _userName = string.Empty;
      private string _userId = string.Empty;

      public RevisionListener(string userName, string userId)
      : base()
      {
      this._userName = userName;
      this._userId = userId;
      }

      public void NewRevision(object revisionEntity)
      {
      var casted = revisionEntity as RevisionDetails;

      if (casted != null)
      {
      casted.UserName = this._userName;
      casted.UserId = this._userId;
      }
      }


      }










      share|improve this question













      I am in dire need of your help. I have migrated some legacy .Net web API applications to .net core and get it all working except the Envers piece of it. The major problem I am facing is to pass user name to the RevisionListener. As RevisionListener does not support DI I am not able to inject HttpContextAccessor to get the context. Alternatively if I use static HttpContextAccessor I am running with same context from two different request.



      Even if I use "IHttpContextAccessor " due t static nature of the class Revision table is holding the same context between two requests from 2 different users.



      Any example will be appreciated!



      Here is the code I am using to configure nHibernate



      // NHibernateExtension method to onboard nhiberbate to .net core
      public static class NHibernateExtension



      {
      public static void AddNhibernate(this IServiceCollection services, string connectionString,string schemaName )

      {



      services.AddSingleton((provider) =>

      {

      var cfg = new NHibernate.Cfg.Configuration();

      cfg.Configure("hibernate.cfg.xml");

      cfg.SetProperty("connection.connection_string", connectionString);

      cfg.AddProperties(new Dictionary<string, string>

      {

      { NHibernate.Cfg.Environment.DefaultSchema, schemaName }

      });

      cfg.AddMapping(NHibernateConfig.GetMappings());



      var enversConfiguration = GetEnversConfiguration();

      cfg.SetEnversProperty(ConfigurationKey.DefaultSchema, "Audit");

      cfg.IntegrateWithEnvers(enversConfiguration);





      return cfg;

      });



      services.AddSingleton((provider) => provider.GetService<NHibernate.Cfg.Configuration>().BuildSessionFactory());



      services.AddScoped((provider) => provider.GetService<ISessionFactory>().OpenSession());

      }





      private static FluentConfiguration GetEnversConfiguration()

      {

      var enversConf = new FluentConfiguration();



      var userId = HttpContext.Current?.Request?.Headers["user_name"];

      var userName = HttpContext.Current?.Request?.Headers["name"];



      RevisionListener rn = new RevisionListener(userName, userId);

      enversConf.SetRevisionEntity<RevisionDetails>(x => x.Id, x => x.RevisionTimestamp, rn);

      enversConf.Audit<PrinterMapping>().SetTableInfo(x => x.Value = typeof(PrinterMapping).Name);

      enversConf.Audit<Label>().SetTableInfo(x => x.Value = typeof(Label).Name);

      enversConf.Audit<Language>().SetTableInfo(x => x.Value = typeof(Language).Name);

      enversConf.Audit<Translation>().SetTableInfo(x => x.Value = typeof(Translation).Name);

      return enversConf;

      }



      }


      //this provides HttpContext through IHttpContextAccessor



      public static class HttpContext



      {

      private static IHttpContextAccessor _contextAccessor;



      public static Microsoft.AspNetCore.Http.HttpContext Current => _contextAccessor.HttpContext;



      internal static void Configure(IHttpContextAccessor contextAccessor)

      {

      _contextAccessor = contextAccessor;

      }

      }


      */Listener****/



      public class RevisionListener : IRevisionListener {



      private string _userName = string.Empty;
      private string _userId = string.Empty;

      public RevisionListener(string userName, string userId)
      : base()
      {
      this._userName = userName;
      this._userId = userId;
      }

      public void NewRevision(object revisionEntity)
      {
      var casted = revisionEntity as RevisionDetails;

      if (casted != null)
      {
      casted.UserName = this._userName;
      casted.UserId = this._userId;
      }
      }


      }







      asp.net-core hibernate-envers






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 at 18:02









      Pratip Bagchi

      11




      11





























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53267706%2fadd-nhibernate-with-net-core-add-auditing-through-httpcontext%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53267706%2fadd-nhibernate-with-net-core-add-auditing-through-httpcontext%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

          ComboBox Display Member on multiple fields

          Is it possible to collect Nectar points via Trainline?