2
votes

From the tutorial referenced below, there is a controller:

public class HomeController : Controller
{
  MvcNinjectExample.Logging.ILogger _logger;

  public HomeController(MvcNinjectExample.Logging.ILogger logger)
  {
    _logger = logger;
  }

  public ActionResult Index()
  {
    _logger.LogMessage("Running index page!");

    return Content("Message logged");
  }
}

As per the following binding...

public static void RegisterServices(IKernel kernel)
{
  kernel.Bind<ILogger>().To<TextFileLogger>();
}

... The TextFileLogger() is called whenever the HomeController is instantiated. Correct?

The tutorial goes on to say this:

If you were to change this to use our EventFileLogger implementation as in one of the earlier examples, you will see that all you would have to do is create the implementation, make it implement ILogger and then register it in your kernel bindings. No changes to any controllers which use it are necessary.

My question is:

If I created a new class called EventFileLogger() which implemented ILogger and then created the binding like kernel.Bind<ILogger>().To<EventFileLogger>();, how does Ninject know to use my new EventFileLogger() and not the other binding for TextFileLogger() when the HomeController is instantiated?

Ref. http://stevescodingblog.co.uk/dependency-injection-beginners-guide/

1

1 Answers

2
votes

You have misunderstood.

Ninject cannot (by default) decide which concrete class to use given two identical bindings. It does, however, support contextual bindings. For example, you can have TextFileLogger injected into your HomeController and another concrete implementation somewhere else... but only when you explicitly state such requirements.

The author means that, if you change the binding (that is, edit the To<>() part), it will all magically continue working with whatever you put there that implements ILogger.