1

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).

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Assaf Stone
  • 6,309
  • 1
  • 34
  • 43
  • There's a sample in https://github.com/ninject/ninject/wiki/Contextual-Binding -- it might move (or be removed) though, esp as @Remo's answer is definitely the best general advice – Ruben Bartelink Mar 28 '11 at 22:45
  • See also http://stackoverflow.com/questions/6781418/using-ninject-to-fill-log4net-dependency/9940470#9940470 – Ruben Bartelink Mar 30 '12 at 09:40

1 Answers1

2
  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

Remo Gloor
  • 32,665
  • 4
  • 68
  • 98