(Paper) Dependency Injection in C# With Ninject
(Paper) Dependency Injection in C# With Ninject
class Program
{
static void Main(string[] args)
{
IMailSender mailSender = new MockMailSender();
FormHandler formHandler = new FormHandler(mailSender);
formHandler.Handle("[email protected]");
Console.ReadLine();
}
}
This is an example of manual dependency injection,
because we’re not relying on any framework to do the heavy
lifting for us. The above code is fine, and will work like a
charm. But this approach will become progressively harder
as the number of dependencies increases. After all, you’ll
have to add one constructor parameter for every new
dependency in the class you’re instantiating. This can be
quite infuriating. Therefore, we need a framework to take
care of this. This is where Ninject, or any other DI
framework, comes in.
using Ninject;
class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
var mailSender = kernel.Get<IMailSender>();
Console.ReadLine();
}
}
When running this code, your console will say ‘Mocking mail
to ….’, which is also what we expected. The dependency
injection is working! The code is creating a Ninject
Kernel that resolves our entire chain of dependencies. We
tell Ninject to load the bindings from the executing
assembly. This is the most common scenario. In this case,
your Bindings class should live in one of the assemblies
included in your executing project. Practically speaking, this
means that your Bindings class will usually live in your
website, webservice, windows service, console application or
unit test project, as they are at the top of the chain of
executing code. For every chain / context (website, unit
tests, console) you can create a different Bindings class with
different configurations. For example, you can change the
Bindings class to use the MailSender wherever IMailSender
is used:
Check out the code for a simple console app here (Visual
Studio 2013):
https://bitbucket.org/cverwijs/examples.ninject