[Under Construction!!!]
================================================================
Dependency Injection:
================================================================
Description:
Dependency injection is a software design pattern that allows a choice of component to be made at run-time rather than compile time. This can be used, for example, as a simple way to load plugins dynamically or to choose mock objects in test environments vs. real objects in production environments. This software design pattern injects the depended-on element (object or value etc) to the destination automatically by knowing the requirement of the destination. Another pattern, called dependency lookup, is a regular process and reverse process to dependency injection.
DI is also known as Inversion of Control (IOC). It is a design pattern that remove tight coupling between dependent components. It facilitates the design and implementation of loosely coupled, reusable, and testable objects in your software designs by removing dependencies that often inhibit reuse. Instead of compile time dependencies it offers runtime loading and initialization of components, which makes solutions load on demand.
There are following advantages and disadvantages of Dependency Injection
Primary advantages:
In this injection type, dependencies can be injected through parameters in constructor of class. It is widely used in Unit Testing with Mocking objects.
Here is example (Please note: this example is not real solution of credit card validation, it is just for example purpose).
In below code I am injecting instance of VisaCard and MasterCard classes from
outside to validate card no.
Output
Validate Card
Validating Visa Card Result: True
Validating Master Card Result: True
Setter Injection
Setter injection uses properties to inject the dependencies, which lets you create and use resources as late as possible. It's more flexible than constructor injection because you can use it to change the dependency of one object on another without having to create a new instance of the class or making any changes to its constructor.Here's an example which will inject creditcard instance through properties in that case we don’t need to create instance of CreditCardValidator again.
Interface Injection
Interface injection, by using a common interface that other classes need to implement to inject dependencies.
The following code shows an example in which the classes use the ICreditCard interface as a base contract to inject an instance of any of the credit card classes (VISA or MasterCard) into the CreditCardValidator class. Both the credit card classes VISA and MasterCard implement the ICreditCard interface:
DI Frameworks:
1. Unity:
The Unity Application Block (Unity) is a lightweight extensible dependency injection container with support for constructor, property, and method call injection.
Unity is a general‐purpose container for use in any type of .NET Framework‐based application. It provides all of the features commonly found in dependency injection mechanisms, including methods to register type mappings and object instances, resolve objects, manage object lifetimes, and inject dependent objects into the parameters of constructors and methods and as the value of properties of objects it resolves.
Why you should implement Unity ?
First you need to register
interface with concrete object,
when you call resolve method of instance IUnityContainer, it will call
constructor and find concrete object from IUnityContainer.
Setter Injection with Unity
For property injection you just need to put [Dependency] attributes on property, Unity framework will automatically create concrete object. The following code demonstrates property injection.
REFERENCES
http://unity.codeplex.com/
http://martinfowler.com/articles/injection.html
--------------------------------------------------------
Intercepting Calls to Objects in C# using Unity:
------------------------------------------------------------------------------------------------------
2. Ninject:
It is mainly used in the context of ASP.Net MVC projects.
For that first we have to bind the interfaces with implementations, in our case we have to bind the IWeatherStation with WeatherStation and IDisplay with ConsoleDisplay. We can do that through two ways either directly using the Bind methods of Kernel or creating a module and passing it to the Kernel. In our example we are going to use the first option but in big applications it is a good idea to bind the things through modules and pass them to the Kernel.
We have to bind the things in the composition root of the application. The composition root is different in different applications, in console applications it is the Main() method.
First create an instance of the StandardKernel.
If everything is working fine we will see a random weather condition displayed in the console.
Download Sample
------------------------------------------------------
source: http://www.dotnetcurry.com/ShowArticle.aspx?ID=829
Before we jump into Ninject and Dependency Injection, let us quickly run through the basics of DI. The basic premises of DI are
But in such a scheme, each layer instantiates the layer above it and the View layer access the Data Access Layer too. This is classic example of a hard coupled system.
Instead of the above, if we define the Data Access Interfaces in our Domain layer and implement those interfaces in the Data layer, the dependencies would get inverted and Data Layer would then be dependent on the Domain layer. The View layer continues to refer to the Domain layer. Since View layer doesn’t have access to EntityFramework or the Data Access Objects, how does it deal with the data? We define a layer of Plain Old CLR Objects (POCOs) in the Domain Layer. These POCOs are our Data Transfer Object (DTOs) between Data and Domain layers.
Since the Domain layer only defines Interfaces to the data layer (aka Repository Interfaces), there is nothing to new up in the View layer. The concrete instance of the Domain layer is passed in to the Domain layer. The concrete instance is created in the Composition Root.
Now our application layering looks as follows:
This layer has

The Composition Root is essentially determining the concrete instance (SqlBlogPostRepository) for an interface (IBlogPostRepository), instantiating the concrete instance.
Next the code is fetching an instance of IControllerFactory that is responsible for generating all the controllers required in the MVC application. The Composition Root is also injecting the repository into the Controller Factory instance, thus making the Repository available for use in the View layer.
For a simple application as this sample, this discovery instantiating and injection looks trivial enough, but imagine a project with multiple controllers and repositories and other related dependencies, trying to track all of those manually and wiring them in the composition root will soon become a nightmare and devs in the team will start trying to hack their way around. This is where Inversion of Control Containers (or IoC Containers) comes into picture. IoC containers when configured to map an interface to a concrete type, can generate a new concrete instance whenever required. This automates the process of dependency wiring. As long as everyone is referring to Interfaces and the IoC container knows how to get a concrete class for that Interface, we are good. Ninject is once of the newer and popular IoC containers. It’s an open source project that is actively worked upon and has a vibrant community.
- Open the (Nuget) Package Manager Console and use the following commands
Install-package Ninject
Install-package Ninject.MVC3
This installs the required dependencies for Ninject in an MVC application.
Step 2: Override the ‘CreateKernel’ method from the NinjectHttpApplication class in Global.asax and add the following
Step 3: Mapping the Dependencies.
- Add reference to FunWithSignalR.Data to your composition root (currently this is the web project don’t worry about the seemingly backwards dependency coupling, we will decouple it later).
- Create a new Class called DependencyMapper and inherit it from NinjectModule
- Override the Load() method and map the IBlogPostRepository to SqlBlogPostRepository as follows:
This code tells Ninject that whenever IBlogPostRepository is requested for, instantiate SqlBlogPostRepository with the given arguments in its constructor.
This method is where we will map similar dependencies when our project grows in size.
- Note how we pass constructor arguments to Ninject so that Ninject can use them at the time of type initialization.
- Setup the Application Start. Comment out the Application_Start() event’s code and add an override for the OnApplicationStarted method in the Global.asax
- If you run your application now, it will be up and running fine using Ninject IoC Container! W00t!
That covers up our migration from Poor Man’s DI to using Ninject as your IoC Container in ASP.NET MVC. For a sample project like ours, the benefits seem negligible but for larger projects having an IoC Container, the benefit goes a long way in helping manage object instantiation, Interface based development and therefore loosely coupled apps.
IoC Containers support various ‘discovery modes’ for concrete instances. They are roughly bunched into
To solve our problem of having all references in the View layer, we will create a ‘Bootstrap’ project and add all references to that project. Then call the bootstrap from our Application start up. This way we can avoid the referencing issues.
1. Add a new ClassLibrary project and call it FunWithSignalR.CompositionRoot
2. Remove the default Class1.
3. Remove EntityFramework, FunWithSignalR.Data dependencies from the FunWithSignalRDI.Web project and add FunWithSignalR.Data and FunwithSignalRDI.Domain to the FunWithSignalR.CompositionRoot.
4. Add Ninject dependencies to the CompositionRoot project by using the following command
install-package Ninject
Note you don’t need Ninject.MVC3 package here.
5. Move DependencyMapper.cs to the CompositionRoot project and update Namespaces are required
6. Add references to FunWithSignalR.Data, FunWithSignalR.Domain to the CompositionRoot
7. Add reference to System.Configuration.dll to the CompositionRoot.
8. Back in the Global.asax of the Web project, update the CreateKernel() method to include the CompositionRoot.
9. Remove the old BlogControllerFactory and CompositionRoot classes from the Web project.
10. Run the application. Voila! We have Ninject + ASP.NET MVC going like a charm.
Utility of the IoC Containers becomes quickly evident in very large projects.
For our well-experienced readers, hope this was a sufficient ‘quick-summary’. For our readers getting into DI and IoC we hope to have provided you with enough nudge to first adopt DI and next use IoC containers as a regular development practice.
Download the source code
================================================================
Dependency Injection:
================================================================
Description:
Dependency injection is a software design pattern that allows a choice of component to be made at run-time rather than compile time. This can be used, for example, as a simple way to load plugins dynamically or to choose mock objects in test environments vs. real objects in production environments. This software design pattern injects the depended-on element (object or value etc) to the destination automatically by knowing the requirement of the destination. Another pattern, called dependency lookup, is a regular process and reverse process to dependency injection.
DI is also known as Inversion of Control (IOC). It is a design pattern that remove tight coupling between dependent components. It facilitates the design and implementation of loosely coupled, reusable, and testable objects in your software designs by removing dependencies that often inhibit reuse. Instead of compile time dependencies it offers runtime loading and initialization of components, which makes solutions load on demand.
There are following advantages and disadvantages of Dependency Injection
Primary advantages:
- Loose coupling
- Centralized configuration
- Easily testable
- Debugging components while development because finding concrete objects may be tedious task.It make code harder to understand and more difficult to modify.
- Wiring instances together can become a nightmare if there are too many instances and many dependencies that need to be addressed.
- Constructor Injection
- Setter Injection
- Interface-based injection
In this injection type, dependencies can be injected through parameters in constructor of class. It is widely used in Unit Testing with Mocking objects.
Here is example (Please note: this example is not real solution of credit card validation, it is just for example purpose).
01.
public
class
CreditCardValidator
02.
{
03.
private
ICreditCard
_card;
04.
05.
public
CreditCardValidator(ICreditCard card)
06.
{
07.
_card = card;
08.
}
09.
10.
public
bool
Validate()
11.
{
12.
return
_card.Validate();
13.
}
14.
}
01.
public
interface
ICreditCard
02.
{
03.
string
CardNo {
set
; }
04.
bool
Validate();
05.
}
06.
public
class
MasterCard : ICreditCard
07.
{
08.
private
string
_cardno;
09.
public
bool
Validate()
10.
{
11.
return
true
;
12.
}
13.
14.
public
string
CardNo
15.
{
16.
set
{ _cardno = value;
}
17.
}
18.
19.
}
20.
public
class
VISA : ICreditCard
21.
{
22.
private
string
_cardno;
23.
24.
public
bool
Validate()
25.
{
26.
return
true
;
27.
}
28.
29.
public
string
CardNo
30.
{
31.
set
{ _cardno = value;
}
32.
}
33.
}
34.
35.
static
void
Main(
string
[]
args)
36.
{
37.
ICreditCard visaCard =
new
VISA();
38.
visaCard.CardNo =
"123123123"
;
39.
ICreditCard mastercard =
new
MasterCard();
40.
visaCard.CardNo =
"456456456"
;
41.
42.
Console.WriteLine(
"Validate Card"
);
43.
CreditCardValidator validator =
new
CreditCardValidator(visaCard);
44.
Console.WriteLine(
"Validating Visa Card Result: {0}"
,
validator.Validate());
45.
validator =
new
CreditCardValidator(mastercard);
//again creating instance
46.
Console.WriteLine(
"Validating Master Card Result: {0}"
,
validator.Validate());
47.
48.
Console.ReadLine();
49.
}
50.
51.
}
Validate Card
Validating Visa Card Result: True
Validating Master Card Result: True
Setter Injection
Setter injection uses properties to inject the dependencies, which lets you create and use resources as late as possible. It's more flexible than constructor injection because you can use it to change the dependency of one object on another without having to create a new instance of the class or making any changes to its constructor.Here's an example which will inject creditcard instance through properties in that case we don’t need to create instance of CreditCardValidator again.
01.
public
class
CreditCardValidator
02.
{
03.
private
ICreditCard
_card;
04.
public
ICreditCard Card
05.
{
06.
get
{
return
_card; }
07.
set
{ _card = value; }
08.
}
09.
public
bool
Validate()
10.
{
11.
return
_card.Validate();
12.
}
13.
}
14.
static
void
Main(
string
[]
args)
15.
{
16.
ICreditCard visaCard =
new
VISA();
17.
visaCard.CardNo =
"123123123"
;
18.
ICreditCard mastercard =
new
MasterCard();
19.
visaCard.CardNo =
"456456456"
;
20.
Console.WriteLine(
"Validate Card"
);
21.
CreditCardValidator validator =
new
CreditCardValidator();
//creating instance one time only
22.
validator.Card = visaCard;
//setter injection
23.
Console.WriteLine(
"Validating Visa Card Result: {0}"
,
validator.Validate());
24.
validator.Card = mastercard;
//setter injection
25.
Console.WriteLine(
"Validating Master Card Result: {0}"
,
validator.Validate());
26.
Console.ReadLine();
27.
return
;
28.
}
Interface injection, by using a common interface that other classes need to implement to inject dependencies.
The following code shows an example in which the classes use the ICreditCard interface as a base contract to inject an instance of any of the credit card classes (VISA or MasterCard) into the CreditCardValidator class. Both the credit card classes VISA and MasterCard implement the ICreditCard interface:
01.
public
interface
ICreditCard
02.
{
03.
string
CardNo {
set
; }
04.
bool
Validate();
05.
}
06.
public
class
MasterCard : ICreditCard
07.
{
08.
private
string
_cardno;
09.
public
bool
Validate()
10.
{
11.
return
true
;
12.
}
13.
public
string
CardNo
14.
{
15.
set
{ _cardno = value;
}
16.
}
17.
}
18.
public
class
VISA : ICreditCard
19.
{
20.
private
string
_cardno;
21.
public
bool
Validate()
22.
{
23.
return
true
;
24.
}
25.
public
string
CardNo
26.
{
27.
set
{ _cardno = value;
}
28.
}
29.
}
DI Frameworks:
1. Unity:
The Unity Application Block (Unity) is a lightweight extensible dependency injection container with support for constructor, property, and method call injection.
Unity is a general‐purpose container for use in any type of .NET Framework‐based application. It provides all of the features commonly found in dependency injection mechanisms, including methods to register type mappings and object instances, resolve objects, manage object lifetimes, and inject dependent objects into the parameters of constructors and methods and as the value of properties of objects it resolves.
Why you should implement Unity ?
- You wish to build your application according to sound object oriented
principles (following the
five principles of class design, or SOLID), but doing so would result in large amounts of
difficult‐to‐maintain code to connect objects together. - Your objects and classes may have dependencies on other objects or classes.
- Your dependencies are complex or require abstraction.
- You want to take advantage of constructor, method, or property call injection features.
- You want to manage the lifetime of object instances.
- You want to be able to configure and change dependencies at run time.
- You want to intercept calls to methods or properties to generate a policy chain or pipeline containing handlers that implement crosscutting tasks.
- You want to be able to cache or persist the dependencies across post backs in a Web application.
01.
using
System;
02.
using
System.Collections.Generic;
03.
using
System.Linq;
04.
using
System.Text;
05.
using
Microsoft.Practices.Unity;
06.
07.
namespace
ParallelLibrarySamples
08.
{
09.
class
Program
10.
{
11.
12.
static
void
Main(
string
[] args)
13.
{
14.
15.
IUnityContainer uContainer =
new
UnityContainer();
16.
uContainer.RegisterType();
17.
//it will automatically fires constructor of
CreditCardValidator class
18.
CreditCardValidator myInstance =
uContainer.Resolve();
19.
}
20.
}
21.
22.
public
class
CreditCardValidator
23.
{
24.
public
CreditCardValidator(ICreditCard card)
25.
{
26.
//card is VISA type
27.
card.Validate();
28.
}
29.
}
30.
}
1.
uContainer.RegisterType();
Setter Injection with Unity
For property injection you just need to put [Dependency] attributes on property, Unity framework will automatically create concrete object. The following code demonstrates property injection.
01.
static
void
Main(
string
[]
args)
02.
{
03.
04.
IUnityContainer uContainer =
new
UnityContainer();
05.
uContainer.RegisterType();
06.
07.
// CreditCardValidator myInstance =
uContainer.Resolve();
08.
CreditCardValidator myinstance =
new
CreditCardValidator();
09.
myinstance.Validate();
10.
}
11.
public
class
CreditCardValidator
12.
{
13.
14.
private
ICreditCard
_card;
15.
16.
[Dependency]
17.
public
ICreditCard Card
18.
{
19.
get
{
return
_card; }
20.
set
{ _card = value; }
21.
}
22.
23.
public
bool
Validate()
24.
{
25.
return
_card.Validate();
26.
}
27.
}
http://martinfowler.com/articles/injection.html
--------------------------------------------------------
Intercepting Calls to Objects in C# using Unity:
The best types in object oriented systems are ones that have a single
responsibility. But as systems grow, other concerns tend to creep in. System
monitoring, such as logging, event counters, parameter validation, and exception
handling are just some examples of areas where this is common. If we implement
these cross cutting concerns, it will require large amounts of repetitive code
in application. Intercepting calls to object is not direct implementation in
.Net as it doesn’t support full Aspect Oriented programming concepts (like cross
cutting, point cut etc ).There are many library available which supports AOP
concepts in .Net like AspectF, Unity, PostSharp, Spring.Net etc..
I am taking example from Unity Framework to intercept calls to object.
For example if I want to log every method call in class then we will need to put logging block in all methods, this is repetitive process.
Following code is syntax for interception call:
I start with concrete implementation of above code:
Interceptor is class which encapsulate interceptor behavior and should
implement IInterceptionBehavior interface. Invoke method will be call before
every method that is intercepted.
Above Invoke method will call before method, you can execute any code before
and after called method. getNext() delegate type is
passed to each interceptor's Invoke method. Call the delegate to get the next
delegate to call to continue the chain.
Output
You can download code of this example here
I am taking example from Unity Framework to intercept calls to object.
For example if I want to log every method call in class then we will need to put logging block in all methods, this is repetitive process.
Following code is syntax for interception call:
1.
IUnityContainer container =
new
UnityContainer();
2.
container.AddNewExtension();
3.
container.RegisterType(
4.
new
Interceptor(),
5.
new
InterceptionBehavior(),
6.
new
AdditionalInterface());
01.
static
void
Main(
string
[]
args)
02.
{
03.
IUnityContainer container =
new
UnityContainer();
04.
container.AddNewExtension();
05.
container.RegisterType(
06.
new
Interceptor(),
07.
new
InterceptionBehavior()
08.
);
09.
10.
IDAL dal = container.Resolve();
11.
12.
dal.MethodForLoggingA();
13.
14.
Console.Read();
15.
}
01.
public
class
Interceptor : IInterceptionBehavior
02.
{
03.
public
IEnumerable GetRequiredInterfaces()
04.
{
05.
return
Type.EmptyTypes;
06.
}
07.
08.
public
IMethodReturn
Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
09.
{
10.
/* Call the method that was intercepted
*/
11.
string
className =
input.MethodBase.DeclaringType.Name;
12.
string
methodName =
input.MethodBase.Name;
13.
string
generic =
input.MethodBase.DeclaringType.IsGenericType ?
string
.Format(
"<{0}>"
,
14.
input.MethodBase.DeclaringType.GetGenericArguments().ToStringList())
:
string
.Empty;
15.
string
arguments =
input.Arguments.ToStringList();
16.
17.
string
preMethodMessage
=
string
.Format(
"{0}{1}.{2}({3})"
, className, generic,
methodName, arguments);
18.
Console.WriteLine(
"PreMethodCalling: "
+ preMethodMessage);
19.
//Logging
20.
Logger.Instance.Log(preMethodMessage);
21.
//Invoke method
22.
IMethodReturn msg = getNext()(input, getNext);
23.
//Post method calling
24.
string
postMethodMessage =
string
.Format(
"{0}{1}.{2}() ->
{3}"
, className, generic, methodName, msg.ReturnValue);
25.
Console.WriteLine(
"PostMethodCalling: "
+
postMethodMessage);
26.
//Logging
27.
Logger.Instance.Log(postMethodMessage);
28.
return
msg;
29.
}
30.
31.
public
bool
WillExecute
32.
{
33.
get
{
return
true
; }
34.
}
35.
}
36.
37.
public
class
DAL : AOPExample.IDAL
38.
{
39.
public
virtual
void
MethodForLoggingA()
40.
{
41.
Console.WriteLine(
"Called MethodForLoggingA"
);
42.
}
43.
public
void
MethodForLoggingB()
44.
{
45.
Console.WriteLine(
"Called MethodForLoggingB"
);
46.
}
47.
public
void
MethodForLoggingC()
48.
{
49.
Console.WriteLine(
"Called MethodForLoggingC"
);
50.
}
51.
}
Output

You can download code of this example here
------------------------------------------------------------------------------------------------------
2. Ninject:
It is mainly used in the context of ASP.Net MVC projects.
"Ninject is a lightweight
dependency injection framework for .NET applications. It helps you split your
application into a collection of loosely-coupled, highly-cohesive pieces, and
then glue them back together in a flexible manner. By using Ninject to support your software's architecture,
your code will become easier to write, reuse, test, and modify."
Important features of Ninject
- Provide fluent interface
- Light-weight (122 KB, version-3.0.015)
- Faster because of lightweight code generation
- Extensible (provide extensions for MVC, WCF and more)
Modules
The Modules are the components that are used to register types. Modules act as independent segments of an application that takes care of binding all the interfaces with implementations of that segment. All the modules should implement the interface INinjectModule. Ninject comes with a built-in abstract class NinjectModule that implements this interface. This abstract class contains a single abstract method Load where we bind the interfaces with concrete types.class WarriorModule : NijnectModule { public override Load() { Bind().To (); } }
Kernel
In Ninject the Kernel is the component that controls everything. We can directly bind the interfaces with implementations into Kernel or we can pass them wrapped as modules. Whenever we need any implementation of the mapped interface we can get it right away from the Kernel. Ninject itself comes with a built-in Kernel called StandardKernel.// add bindings directly into the kernel var kernel = new StandardKernel(); kernel.Bindor().To ();
// supply bindings as a module var kernel = new StandardKernel(WarriorModule);
// get an IWeapon implementation var weapon = kernel.Get();
Lets try a sample!
Before trying the sample you can download the Ninject assemblies and extensions from here. In this sample console application we have a WeatherStation class that randomly displays weather condition through an IDisplay implementation. The dependencies of the WeatherStation are injected through the constructor.interface IWeatherStation { void DisplayReport(); } class WeatherStation : IWeatherStation { private readonly IDisplay _display; private readonly WeatherCondition[] _weatherConditions; private readonly Random _random; public WeatherStation(IDisplay display, WeatherCondition[] weatherConditions) { _display = display; _weatherConditions = weatherConditions; _random = new Random(); } public void DisplayReport() { var weatherCondition = _weatherConditions[_random.Next(0, _weatherConditions.Length)]; _display.SetColor(weatherCondition.Color); _display.Write(String.Format(" {0} @ {1}", weatherCondition.Name, DateTime.Now.ToLongTimeString())); _display.ResetColor(); } }The IDisplay interface has methods for both to display text and to set foreground color for the text. The ConsoleDisplay class implements IDisplay interface which writes the text into the console.
interface IDisplay { void Write(string message); void SetColor(string color); void ResetColor(); } class ConsoleDisplay : IDisplay { public void Write(string message) { Console.WriteLine(message); } public void SetColor(string color) { Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), color); } public void ResetColor() { Console.ForegroundColor = ConsoleColor.Gray; } }Our goal is when we ask for IWeatherStation, Ninject should give us an implementation of that with all the dependencies created automatically.
For that first we have to bind the interfaces with implementations, in our case we have to bind the IWeatherStation with WeatherStation and IDisplay with ConsoleDisplay. We can do that through two ways either directly using the Bind methods of Kernel or creating a module and passing it to the Kernel. In our example we are going to use the first option but in big applications it is a good idea to bind the things through modules and pass them to the Kernel.
We have to bind the things in the composition root of the application. The composition root is different in different applications, in console applications it is the Main() method.
First create an instance of the StandardKernel.
var kernel = new StandardKernel();
Map the interfaces with concrete types. We can easily map the IDisplay interface with the ConsoleDisplay using the Bind and To methods. kernel.BindWhile mapping the IWeatherStation to the WeatherStation we need to pass both an IDisplay implementation and collection of WeatherConsition instances to the constructor. For the IDisplay implementation Ninject automatically passes the ConsoleDisplay instance. But for the weatherConditions parameter we have to pass it manually using the WithConstructorArgument method. The WithConstructorArgument takes both the parameter name and value as arguments.().To ();
kernel.BindThe setup code is complete. Now we can get an instance of IWeatherStation implementation through the Get method of the kernel at any place.().To ().WithConstructorArgument ( "weatherConditions", new WeatherCondition[] { new WeatherCondition{ Name = "HOT", Color = "Yellow" }, new WeatherCondition{ Name = "COLD", Color = "Blue" }, new WeatherCondition{ Name = "STORM", Color = "DarkGray" }, new WeatherCondition{ Name = "SNOW", Color = "White" }, new WeatherCondition{ Name = "WINDY", Color = "Gray" } } );
var weatherStation = kernel.Get(); weatherStation.DisplayReport();
If everything is working fine we will see a random weather condition displayed in the console.
Download Sample
------------------------------------------------------
source: http://www.dotnetcurry.com/ShowArticle.aspx?ID=829
Before we jump into Ninject and Dependency Injection, let us quickly run through the basics of DI. The basic premises of DI are
- All dependencies of a class should be passed (injected) into the class instead of being instantiated directly. In other words avoid new-ing up of interdependent layers.
- Code to Interfaces instead of concrete implementations.
- All Class instantiation and object lifecycle management should be done at a central location referred to as the ‘Composition Root’.
- Inversion of Control (IoC) Containers refers to frameworks that help manage the object instantiation and lifecycle.
- You can do DI without IoC containers, in such cases the pattern is referred to as ‘poor-man’s-DI’ and you have to hand code the object instantiation and lifecycle management.
A Simple Application
For the purposes of our discussion, we will take a simple three-layer application with one Entity on which we will be doing Create Read Update and Delete (CRUD) operations. A standard layering scheme looks like the following
But in such a scheme, each layer instantiates the layer above it and the View layer access the Data Access Layer too. This is classic example of a hard coupled system.
Instead of the above, if we define the Data Access Interfaces in our Domain layer and implement those interfaces in the Data layer, the dependencies would get inverted and Data Layer would then be dependent on the Domain layer. The View layer continues to refer to the Domain layer. Since View layer doesn’t have access to EntityFramework or the Data Access Objects, how does it deal with the data? We define a layer of Plain Old CLR Objects (POCOs) in the Domain Layer. These POCOs are our Data Transfer Object (DTOs) between Data and Domain layers.
Since the Domain layer only defines Interfaces to the data layer (aka Repository Interfaces), there is nothing to new up in the View layer. The concrete instance of the Domain layer is passed in to the Domain layer. The concrete instance is created in the Composition Root.
Now our application layering looks as follows:

How does this translate into code?
Well the sample application has the following structure.The Data Layer
This layer has- POCOs used for serialization/deserialization of data from DB, using the EntityFramework. If case of other OR/M it will contain the Data Objects required by the OR/Ms.
- The concrete implementation of the Repositories defined in the Domain Layer
- The translation layer from Domain object to Data object and vice versa.
The Domain Layer
- The Interface definitions for all data access. Only the interfaced that are defined here is accessible to the view layer
- The Domain POCOs
- A Service Layer to manage business rules if any.
The View Layer
- The view markup
- The rendering logic
- The Composition Root. For purposes of simplification, the Composition Root is shown in the View layer but as we will see later, this gives rise to a coupling that we will eventually have to break.

A Closer Look at the Composition Root
Before we jump into an IoC container, lets take a closer look at the Composition Root.
The Composition Root is essentially determining the concrete instance (SqlBlogPostRepository) for an interface (IBlogPostRepository), instantiating the concrete instance.

Next the code is fetching an instance of IControllerFactory that is responsible for generating all the controllers required in the MVC application. The Composition Root is also injecting the repository into the Controller Factory instance, thus making the Repository available for use in the View layer.
For a simple application as this sample, this discovery instantiating and injection looks trivial enough, but imagine a project with multiple controllers and repositories and other related dependencies, trying to track all of those manually and wiring them in the composition root will soon become a nightmare and devs in the team will start trying to hack their way around. This is where Inversion of Control Containers (or IoC Containers) comes into picture. IoC containers when configured to map an interface to a concrete type, can generate a new concrete instance whenever required. This automates the process of dependency wiring. As long as everyone is referring to Interfaces and the IoC container knows how to get a concrete class for that Interface, we are good. Ninject is once of the newer and popular IoC containers. It’s an open source project that is actively worked upon and has a vibrant community.
Getting Started with Ninject
Now that we have seen the code factored to use Poor Man’s DI, we will see how we can nicely transition to using Ninject and see the challenges on the way.Installing Ninject
- Select the web project- Open the (Nuget) Package Manager Console and use the following commands
Install-package Ninject
Install-package Ninject.MVC3
This installs the required dependencies for Ninject in an MVC application.
‘Configuring’ Ninject to be your IoC Container
Step 1: Open Global.asax and change the subclass from System.Web.HttpApplication to Ninject.Web.Common.NinjectHttpApplicationStep 2: Override the ‘CreateKernel’ method from the NinjectHttpApplication class in Global.asax and add the following

Step 3: Mapping the Dependencies.
- Add reference to FunWithSignalR.Data to your composition root (currently this is the web project don’t worry about the seemingly backwards dependency coupling, we will decouple it later).
- Create a new Class called DependencyMapper and inherit it from NinjectModule
- Override the Load() method and map the IBlogPostRepository to SqlBlogPostRepository as follows:

This code tells Ninject that whenever IBlogPostRepository is requested for, instantiate SqlBlogPostRepository with the given arguments in its constructor.
This method is where we will map similar dependencies when our project grows in size.
- Note how we pass constructor arguments to Ninject so that Ninject can use them at the time of type initialization.
- Setup the Application Start. Comment out the Application_Start() event’s code and add an override for the OnApplicationStarted method in the Global.asax

- If you run your application now, it will be up and running fine using Ninject IoC Container! W00t!
That covers up our migration from Poor Man’s DI to using Ninject as your IoC Container in ASP.NET MVC. For a sample project like ours, the benefits seem negligible but for larger projects having an IoC Container, the benefit goes a long way in helping manage object instantiation, Interface based development and therefore loosely coupled apps.
But… you just bunched all the references into the View layer!
Yes, you are right, and it’s a valid objection. If using IoC Containers and DI is the holy grail of decoupled application development, we just shattered that concept. The answer is rather simple. The ‘Composition Root’ of your application HAS to have access to all possible dependencies. Come to think of it, it’s a reasonable expectation. If it is going to be responsible for wiring up Interfaces to Concrete instances, it SHOULD know where to find the concrete instances.IoC Containers support various ‘discovery modes’ for concrete instances. They are roughly bunched into
- XML Configuration
- Configuration via code conventions
- Configuration via code
To solve our problem of having all references in the View layer, we will create a ‘Bootstrap’ project and add all references to that project. Then call the bootstrap from our Application start up. This way we can avoid the referencing issues.
Moving ‘Composition Root’ out of the Web Project
To solve our architectural issue of View layer referring to Data layer directly, we split the code up as follows:1. Add a new ClassLibrary project and call it FunWithSignalR.CompositionRoot
2. Remove the default Class1.
3. Remove EntityFramework, FunWithSignalR.Data dependencies from the FunWithSignalRDI.Web project and add FunWithSignalR.Data and FunwithSignalRDI.Domain to the FunWithSignalR.CompositionRoot.

4. Add Ninject dependencies to the CompositionRoot project by using the following command
install-package Ninject
Note you don’t need Ninject.MVC3 package here.
5. Move DependencyMapper.cs to the CompositionRoot project and update Namespaces are required
6. Add references to FunWithSignalR.Data, FunWithSignalR.Domain to the CompositionRoot

7. Add reference to System.Configuration.dll to the CompositionRoot.
8. Back in the Global.asax of the Web project, update the CreateKernel() method to include the CompositionRoot.
9. Remove the old BlogControllerFactory and CompositionRoot classes from the Web project.
10. Run the application. Voila! We have Ninject + ASP.NET MVC going like a charm.
Conclusion
We just scraped the surface of IoC Containers, specifically Ninject. We just resolved our repository types using the container. We could potentially extract interfaces for our Domain Entities and get the container to resolve them for us too.Utility of the IoC Containers becomes quickly evident in very large projects.
For our well-experienced readers, hope this was a sufficient ‘quick-summary’. For our readers getting into DI and IoC we hope to have provided you with enough nudge to first adopt DI and next use IoC containers as a regular development practice.
Download the source code