ASP.NET MVC2 + Ninject + NLog (+ shared hosting?) = NullReferenceException

后端 未结 4 1530
名媛妹妹
名媛妹妹 2020-12-24 03:28

I have an MVC2 app that\'s based on the Tekpub Starter Site, so it uses Ninject for dependency injection, NLog for logging, and a bunch of other libraries in various places.

相关标签:
4条回答
  • 2020-12-24 03:59

    You could avoid using LogManager.GetCurrentClassLogger() and let Ninject resolve the current class name for you:

    Change the constructor of your NLogLogger class into this:

    public NLogLogger(string currentClassName) 
    {
      _logger = LogManager.GetLogger(currentClassName);
    }
    

    And change the ninject binding to resolve the current classname:

    Bind<ILogger>().To<NLogLogger>()
      .WithConstructorArgument("currentClassName", x => x.Request.ParentContext.Request.Service.FullName);
    

    Additional benefit: your log file now also includes the class name from where the log directive was issued.

    I know my answer is a little bit late to the party, but I was struggling with this myself today and couldn't find the answer anywhere. Maybe this helps someone else.

    0 讨论(0)
  • 2020-12-24 04:01

    It looks like NLog can't run in medium trust: http://nlog-project.org/forum.html#nabble-td1685352

    If you look in the Global, the app logs when it starts up as well as when it shuts down. You should be able to remove that and be happy.

    0 讨论(0)
  • 2020-12-24 04:05

    Shared hosting often has restrictions on reflection etc.

    So my guess is that

    [NullReferenceException: Object reference not set to an instance of an object.] NLog.LogManager.GetCurrentClassLogger() +84

    is related to that - what happens if you get the logger using a meachanism where you pase in a Type that you get at compile time via typeof ?

    0 讨论(0)
  • 2020-12-24 04:09

    I have experienced a similar problem.

    My (simplistic) solution:

    replace these lines

    private Logger Logger = LogManager.GetCurrentClassLogger();
    

    by this line

    private static Logger Logger = LogManager.GetCurrentClassLogger();
    

    The readonly keyword is optional.

    0 讨论(0)
提交回复
热议问题