Search code examples
ninjectninject-2ninject-extensions

Can someone help me set up Ninject 2 with Log4net?


I've been (happily) using Ninject for a while now with some basic scenarios, and would like to give it control of my logging. I noted the existence of the Ninject.Extensions.Logging namespace, and would like to use it, but I'm running into two issues:

  1. I want the logger to be initialized with the type of the class running it (as if I ran LogManager.GetLogger with the GetCurrentMethod().DeclaringType).
  2. I want to be able to easily mock, or "nullify" the logger for unit testing (i.e I don't want to have the logger work), without running into NullReferenceExceptions for not initializing the logger.

Now, I know there are some questions (and even answers) around here, but I couldn't seem to find any that pointed me in the right direction.

I'll appreciate any help (even a "you bone-head" it's here! Linking to something I should have noticed).


Solution

    1. This is the default behavior of the extension
    2. Don't use Ninject to create the object under test in your unit tests. Create an instance manually and pass what ever you want for the logger.

    Best you have a look at the unittests. https://github.com/ninject/ninject.extensions.logging/blob/master/src/Ninject.Extensions.Logging.Tests/Infrastructure/CommonTests.cs