Ninject and Log4Net

2.3k views Asked by At

I can't seem to get ninject to automatically create an instance of ILogger. I have log4net set up in my tests application and configured properly but for some reason when I instantiate the IHouseholdRepository it can't work out the ILogger.

according to this post, I have done everything i need to do: How To Properly Configure Ninject.Extensions.Logging.Log4Net in my MVC3 project

[TestMethod]
public void TestMethod1()
{
    var kernel = new StandardKernel();
    kernel.Bind<IHouseholdRepository>().To<HouseholdRepository>();

    var repo = kernel.Get<IHouseholdRepository>();
    var hh = repo.Find(123456);
}

public HouseholdRepository(ILogger logger, string username)
{
    _logger = logger;
    _username = username;
    _dbContext = new HouseholdDbContext(logger);  // I want to couple my HouseholdDBContect to my repository as it's not going to work with any other DbContext
}

The error I'm getting is:

Test method Rxxx.Tests.LoggingTester.TestMethod1 threw exception: Ninject.ActivationException: Error activating ILogger No matching bindings are available, and the type is not self-bindable. Activation path: 2) Injection of dependency ILogger into parameter logger of constructor of type HouseholdRepository 1) Request for IHouseholdRepository

Suggestions: 1) Ensure that you have defined a binding for ILogger. 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel. 3) Ensure you have not accidentally created more than one kernel. 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name. 5) If you are using automatic module loading, ensure the search path and filters are correct.

3

There are 3 answers

0
user3887850 On

I just had the same problem, and found out it was because I forgot to add the Ninject.Extensions.Logging.Log4net nuget package.

0
Phileosophos On

I had the same failure but with a different reason, and while I didn't find this question helpful I thought I'd add my answer. I was using the ReSharper test runner, which by default does not use a separate app domain for each assembly. The result was that the Ninject kernel was being initialized in such a way as not to bind the required Log4Net extension interfaces.

The fix was to change ReSharper options: ReSharper | Options | Tools | Unit Testing and check "Use separate AppDomain for each assembly". That cleared it up for me. I hope that helps someone else!

0
Jan Bühler On

I had the same problem in a sitecore 8 project, and found out it was because the ninject.dll in the libs/Social folder isn't copied in the /bin folder by the prebuilt script, so each time I clean up the /bin folder I run into this problem. The prebuilt script was built in a time when there were no subfolders in libs…