Dependency Injection in ASP.NET MVC - An Introduction

Posted by: Sumit Maitra , on 2/13/2012, in Category ASP.NET MVC
Views: 163044
Abstract: In this article, we are going to look at a little bit of the theory and then do a code walkthrough to understand basics of Dependency Injection. By the end of the article, we should be clear about the pattern and how to apply it in an ASP.NET MVC application.
As Developers we may have come across the term ‘Dependency Injection’ as a design pattern that helps develop maintainable and de-coupled code. DI is also a way to implement the ‘D’ in SOLID principles. (SOLID as stated by Uncle Bob stands for: Single responsibility, Open closed principle, Liskov substitution principle, Interface segregation principle and Dependency Inversion). Often the association of 'Design Pattern' to anything that we have not dealt with before, typically means it goes into our 'To Do' bucket which becomes very dusty over time. Time to blow the dust away! 
In this article, we are going to look at a little bit of the theory and then do a code walkthrough to understand basics of DI. By the end of the article, we should be clear about the pattern and how to apply it in an ASP.NET application. 


Dependency Injection is often associated with IoC (Inversion of Control) containers. We will not look at any IoC containers. We leave it for the next article in the series.
To get an idea of why we should adopt Dependency Injection (DI), we will first look at an abstract example without DI. Then we'll convert it into one with DI. Let us start off with a standard three-layer web application design. Figure 1 depicts a standard three-layer application.


The arrows above depict direction of coupling, as in the View layer is 'dependent' or 'has reference of' the Domain Layer and the Domain Layer is 'dependent' on the Data Access Layer. This is a common design where each layer represents a project in Visual studio.

On the outset, it looks a perfectly okay design approach. The way to use this would be the View layer code behind (or Controller classes in MVC) would instantiate a Domain Layer class and the domain layer would instantiate a Data access layer class and the calls from the View layer would get chained like this. Initially this seems harmless but programming against concrete instances actually makes our code very tightly coupled and highly 'dependent' on each other. Even though putting data access code separate from business logic code offers some immunity, it still does not give you any design benefit if in the future you had to change data sources say from a local source to a cloud source.

You will be forced to go and change declaration of every instance of the data access layer. In other words it is not a plug-in architecture.

Things get a little more complicated if you are using Data Access Entities (like the Entity Framework) and performing business manipulations on them. That would require the View layer to be 'aware' of these entities and hence refer to the Data Access Layer directly. The above diagram now becomes as follows:


Now this becomes a recipe for disaster because now you have lost control on Data Access and there is nothing stopping from the team newbie calling the data access layer directly and writing a loop in the code behind to manipulate data. Very soon you have your business logic all over the place and your seemingly well thought out layering has gone completely haywire.

Dependency Injection to the rescue

The term Dependency Injection, implies sending a dependency (DAL) into a dependent object (Domain Layer) as opposed to the dependent object controlling life cycle of its dependencies.

That would mean, that the domain layer should not instantiate the Data Access layer, the correct data access instance should be passed to it. Who will pass the instance? Is it the View layer? But does that mean View layer will instantiate the Data Access Layer? No. The View Layer will delegate the object instantiation to a special class called 'COMPOSITION ROOT'. The Composition Root will use configuration and a Factory to determine the correct instance. It will create an instance of the dependency (using reflection) and pass it into the View Layer. Since business layer is our glue between UI and persistence, it is okay to instantiate instance of Business layer directly in the view layer. To make the abstraction complete, the business logic layer should define an abstract class or interface for the Data Access layer to implement. This prevents code instantiation of data access layer anywhere in the Business or View layer. Our design diagram now changes to the following


Notice how the Domain Layer is no longer coupled to Data Access Layer in fact, the DAL now refers to the Domain Layer. This is because the Domain Layer defines the Interfaces that are implemented by the DAL Layer.

Okay, this resolves the dependency creation. But now how will the UI layer deal with data? Answer is 'Domain Objects'. The Domain layer will have to define Domain objects that are POCOs (Plain Old CLR Objects). The Repository implementation will translate the persistent entity Objects in DAL layer to Domain POCOs.

If you are ready to give up with the theory, hang in there for one more minute and we'll get to code.

Before we jump into code we should clarify one more term in DI, Constructor Injection. For DI to work, the dependencies need to be passed in to the dependent objects. The most common way to pass Dependencies is through constructor injection where in, all dependencies are pass as constructor parameters of the dependent objects. For example, in the above diagram, the composition root can pass instances of the Data Access layer only through the constructor of the Controllers (in View layer) and the View layer can pass that instance to the Domain layer only through the constructor of the Business Logic layer. This has an additional side effect i.e. we cannot use empty constructors for DI layers.

Code Walk Through

Okay, enough of theory let us see some code. In this post we will use a modified version of the SignalR application from earlier. The original Code does not use DI. In fact it’s not even split into three projects. Its layers are essentially split by Namespaces. We will take this code and convert it into a DI implementation.

Forking into Dependency Injection

I forked the existing code on my Hg repository so that I can save this branch and then do a fresh branch and Implement it using DI practices.

Step 1: Creating the Domain layer

To begin with, I am going to create the domain layer as follows:

1. Add Domain entities to interact with the View layer thus disconnecting View layer and data layer dependency.

Add reference to System.ComponentModel.DataAnnotations. Add a folder called Model and add a class called BlogPost.cs

The class looks like the following


2. Add a repository Interface to replace the coupling with Data Access layer. All data access calls will be made to the interface. The Interface has the following contract methods.


3. At this point our Domain layer is ready. We don’t really need to introduce any services because there isn’t any business logic that we are handling at the moment. So direct calls to the Repository will suffice. This is what our project looks like


Note: This is a highly simplified Domain layer. In a real life system you will have a service layer that will use an instance of the Repository passed from the View layer, get data from the repository and then pass back filtered/manipulated domain objects. Again, the service layer won’t be instantiating the Data Access layer, instead the DAL will be injected into it. The beauty of the Interface based design is you cannot even instantiate it, so there is no way for a developer to go astray. They are locked in to use constructor injection.

Step 2: Creating the Data Layer

Now we will build the Data Layer.

1. Add a new project called FunWithSignalR.Data
Add references to EntityFramework using Nuget command in the Package Manager Console
PM> Install-package EntityFramework

2. Add a folder Context and move BlogPostContext.cs from the FunWithSignalR.Models folder to this new folder.

3. Add a folder Model and move the BlogPost.cs from the FunWithSignalR.Models folder to this new folder.

Add a new method ToDomainBlogPost() that returns the Domain entity for the current Data entity. The ToDomainBlogPost() entity is a mapping method from a Data object to a Domain object.

The final code looks as follows


4. Add a folder Repository

Add the class SqlBlogPostRepository that implements IBlogPostRepository. The final implementation looks as follows. Note, for the Add and Update methods we are mapping the Domain object coming from View, into a Data object. Again in real life the mapping maybe more complex and data may


This completes the data layer implementation.

Step 3: The Composition Root

With the data layer and domain layer in place, first we’ll get the code to build and then we will then implement the dependency injection part. We will update the BlogPostController as follows:

1. Add a class level instance variable of type IBlogPostRepository

private IBlogPostRepository _repository;

2. Remove all instances of db context and replace them with appropriate repository method calls.

3. Build the solution. Interestingly enough, the solution will build correctly. But if we run it we’ll get a null reference exception for _repository because we have not instantiated with a concrete instance.

4. As discussed briefly earlier, the way to delegate responsibility is to pass the dependencies through constructor injection. The BlogPostController does not have a constructor so we will add one as follows:


5. As we can see above our controller now expects the _repository to be provided (injected with) a repository instance.

6. However the MVC Framework calls the BlogPostController and by default it expects an empty constructor. So how will we inject our dependency? MVC is a mind blowingly pluggable framework. You have to create a custom Controller Factory that derives from the DefaultControllerFactory. The class code is as follows


7. Let us look at the factory class closely

a. It has a dictionary for storing the controllers.
b. The constructor is still taking a parameter of type repository (so we will be injecting the dependency into the controller factory as well).
c. The constructor has a ‘guard method’ to ensure that repository parameter is not null.
d. It then initializes the controller map and adds the two controllers that we have Home and Blog.
e. We next override the CreateController method to return correct controller based on the controllerName and requestContext.

8. With the BlogControllerFactory in place we have ironed out the Constructor injection for the MVC controller. All that is remaining is creation of the CompositionRoot and hooking it up with the application start

a. The CompositionRoot class can be just called so. Add it to the root of the FunWithSignalR project. You could create a new project or folder for it too, but doesn’t really matter.
b. The implementation of the CompositionRoot class is simple. The code listing is as follows


c. There is a local instance variable of the controllerFactory of type IControllerFactory
d. The constructor is public and without parameters. It calls a private static method CreateControllerFactory().
e. The CreateControllerFactory() method is where our dependency instantiation happens.

  • It picks up the Type name from web.config ‘s AppSettings section.
  • Gets the Type by name
  • Builds an instance using Activator.CreateInstance. Notice how we don’t know the instance type at any point because the CompositionRoot is only aware of the Interface. So we cast the instance back as the interface only.
  • This instance is used to instantiate the BlogContollerFactory
  • Returns the BlogControllerFactory to the constructor, that’s saved in the local controllerFactory variable.

f. Update the web.config and add the type name


9. Now all that remains is using the CompositionRoot and letting MVC know that it should use our ControllerFactory instead of the default one. We do this in the Application_Start() event as follows


We initialize the Composition Root. We get the Current ControllerBuilder (provided by the MVC framework) and call the SetControllerFactory method by passing the ControllerFactory from the composition root.

10. Update all the Blog Views to refer to FunWithSignalR.Domain.Model.BlogPost instead of FunWithSignalR.Models.BlogPost.

11. Finally, remember the View layer doesn’t have access to the Data Layer. It uses reflection to generate the dependency, so the Data layer dll must be available as a part of the build. To make that happen add a build event for the solution that copies over the FunWithSignalR.Data.dll over to the View’s bin folder. The command is as follows.

copy "$(SolutionDir)FunWithSignalR.Data\bin\$(ConfigurationName)\*.dll" "$(TargetDir)"

12. I have not included the contents of the packages folder (reduce download size). Instead you will see a .nuget folder with a .targets file. Basically I have enabled “Nuget Package Restore”. Now at Nuget can download required packages at build time. If you are using Visual Web Dev Express, on load you will get a warning saying Solution folders are not supported and you won’t see the .nuget folder in your solution explorer, however the build targets will continue to work.

This completes our wiring up of our entire application.


- Dependency Injection is a Design pattern that enables us to write loosely coupled code (Ref: Dependency Inject in .NET By Mark Seemann) and enforces, dependent object give up control of managing their dependencies and instead let a Composition Root inject the dependencies into them.

- Using a Composition Root in a manner described above is often referred to as ‘Poor man’s DI’ pattern. This is not so much of a bad thing as it is an indicator of lack of Inversion of Control Containers. IoC Containers help in taking away the pain of registering each new object and managing their instances. Some common IoC containers for .NET are Castle Windsor, Unity, Ninject. We will discuss IoC containers in one of our future article.

- DI + Repository + Programming against Interfaces overall help in separation of concerns and greatly improves the overall application maintainability.

- The above design has zero impact on change to View or Data layer.

  • For example, if we were to introduce a new Mobile view we could simply go and build it from scratch while using the exact same Domain and Data Access Layer. All we had to do was ensure the dependencies are created correctly at the Composition Root.
  • Similarly to swap the Sql backend with an Azure backend there would be zero impact on the business layer or the View layer. All that would change was the configuration information providing the concrete type for the Azure repository implementation.
  • In any other design the impact of such changes is much more pervasive and requires touching all layers of an application.


Taking a little bit of time to learn about design patterns prepare us to better recognize practical scenarios of application. Dependency Injection in my book is one of the most important patterns for a seasoned developer. It helps layout a truly flexible, decoupled foundation for what seems a simple problem but will most certainly become a very complex application in future.

The entire source code of this article can be downloaded over here


1. Dependency Injection in .NET by Mark Seemann – A must read for .NET Devs
Principles of Object Oriented Design by Robert C. Martin (Uncle Bob)
Getting a SOLID Start by Uncle Bob.

Give me a +1 if you think it was a good article. Thanks!
Recommended Articles
Sumit is a .NET consultant and has been working on Microsoft Technologies since his college days. He edits, he codes and he manages content when at work. C# is his first love, but he is often seen flirting with Java and Objective C. You can follow him on twitter at @sumitkm or email him at sumitkm [at] gmail

Page copy protected against web site content infringement by Copyscape

User Feedback
Comment posted by Grigory on Monday, February 13, 2012 1:34 PM
Thanks for the good article. Very good intro. Can we expect a continuation?
Comment posted by Sumit on Monday, February 13, 2012 1:48 PM
@Grigory First up, thanks, glad you liked it. Next, yes :-) lookout for - Using DI Containers. Feel free to suggest area of focus.
Comment posted by Marc Gruben on Tuesday, February 14, 2012 12:22 AM
Hi Summit,
Nice overview article! Indeed Seemann's book is the best book available about DI/IoC in .Net.
For the plumping of Dto to domain objects I would use a mapper, like Automapper or Value Injecter, this saves you a lot of time and errors (e.g. when the datamodel changed it will automatically be updated through the layers).
Also a IoC container is a must-have. On NuGet you have Unity MVC3 which is a good starting point!
Comment posted by Fernando Urkijo Cereceda on Tuesday, February 14, 2012 2:45 AM
Hi, nice article I posted some time ago a post in spanish about dependency injection in MVC:
Comment posted by ranu mandan on Tuesday, February 14, 2012 5:49 AM
hi..i have a question.
What the difference between domain object and model object ?
Comment posted by Athens Holloway on Tuesday, February 14, 2012 7:39 AM
Nice post. Which IOC container do you plan to use in your next post? Do you have a preference?
Comment posted by Sumit on Tuesday, February 14, 2012 12:47 PM
@Marc Agree on the Automapper but I wanted to go one concept at a time :).

@Ranu In this example none, the idea is, data object is something that going to get serialized to the database. Only now, we have EF Code first that allows POCOs and even then you may require specific data annotation attributes. For example in EF Domain first the Data object would derive from the EF Entity base class. However the Domain object will always be a POCO and it need not be a one to one mapping with the DB, instead it should encapsulate data as required by the business logic.

@Athens I don't have a preference, let me know if you want something specific. I see one vote for Unity :) by Marc.
Comment posted by Bilal Hasan Khan on Tuesday, February 14, 2012 3:39 PM
Nice one, I would like to know your choice between Ninject, Unity or any other.Also, i understand that the point of article was to go into the concept but would like to know from you, why avoid the already created frameworks like Ninject and reinvent the wheel (pardon my ignorance if you see).
Comment posted by Sumit on Tuesday, February 14, 2012 4:27 PM
@Bilal Choice between Frameworks are often subject to specifics of the problem we are trying to solve. I will try to highlight features/differences between containers and leave the choice to readers.

Regarding your second point, I am not avoiding any framework nor am I advocating 'not to use' any IoC framework. 'Poor man's DI' is the pre-cursor to IoC containers. So I am just stepping through it from a complexity and a bit of history point of view.
Also, I think it's good to know what's happening under the hood :).

Setting up DI Infrastructure without an IoC framework is like getting your hands dirty changing the engine's oil yourself. By that analogy IoC is driving up to the workshop and letting a fluid exchanger do the work for you ;)...
Comment posted by Sumit on Tuesday, February 14, 2012 6:34 PM
Note: The code was built using .NET Framework 4 Platform Update 1. So the target Framework version is 4.0.1. You may get an error if you open it on a System without the Platform Update. VS will ask you if you want to re-target, say Yes. Then in web.config change the  'targetFramework' value to 4.0.0.

Note 2: If you do a clean and rebuild, sometimes you will get an error saying Copy failed. There is a post build event that sometimes fires before the last project has been built. So after a rebuild (if it errors) do a build to complete the Copy post build event.
Comment posted by dwa on Wednesday, February 15, 2012 1:59 AM
Comment posted by Brian on Wednesday, February 15, 2012 8:17 AM
Thanks for this post. I now have a much better understanding of DI in MVC.

I have a general design question. In your setup, the Domain Layer defines an interface for the business logic, but the actual implementation is in the Data Layer. This seems to work perfect here, since all the interface methods are simple CRUD operations, but what do you do when you have more complicated business logic. It doesn't seem like the Data Layer should implement any business logic functionality more complex than CRUD operations.

For a very simple example, maybe you want to increase the user's reputation every time he makes a post. Should the Data Layer know that it needs to update the User object when you creat a new Post object?

Thanks again!
Comment posted by Brian on Wednesday, February 15, 2012 8:33 AM
Thanks for this post. I now have a much better understanding of DI in MVC.

I have a general design question. In your setup, the Domain Layer defines an interface for the business logic, but the actual implementation is in the Data Layer. This seems to work perfect here, since all the interface methods are simple CRUD operations, but what do you do when you have more complicated business logic. It doesn't seem like the Data Layer should implement any business logic functionality more complex than CRUD operations.

For a very simple example, maybe you want to increase the user's reputation every time he makes a post. Should the Data Layer know that it needs to update the User object when you creat a new Post object?

Thanks again!
Comment posted by Sumit on Wednesday, February 15, 2012 11:46 AM
@Brian As briefly mentioned in the Notes, we should do this logic in a class that resides in your Domain layer. You can call it a 'Service' class. In your case, the Reputation changes every-time user submits a post. So instead of calling the _repository.CreateBlogPost(newPost), create an instance of your service layer, in the constructor of the service class pass the _repository. Now call a SavePost method in the Service class, with the newPost and the 'current User'. In this service method you can fetch the current reputation, update it and save both the reputation and Post through the Repository. So basically Repository is responsible for the serialization, you Business Service class does all the logic.

Hope this helps, feel free to mail/tweet to me directly in case of more questions.
Comment posted by Brian on Wednesday, February 15, 2012 12:30 PM
That makes sense. Thanks a lot for the help.
Comment posted by mahendra kumar on Thursday, February 16, 2012 2:57 AM
Hi sir,
i need a job please help me
i have knowledge on C#.NET,ASP.NET,HTML,JAVA SCRIPT
please help me.
Comment posted by bad solution on Thursday, February 16, 2012 10:46 AM
i dont know why .net programmer dont use DI solution that used in java like spring IOC and other
this is article is bad solution
Comment posted by Patrick on Friday, March 16, 2012 10:02 AM
Step 2,

#2 > Add a folder Context and move BlogPostContext.cs from the FunWithSignalR.Models folder to this new folder.

Where is "BlogPostContext.cs"  , I was following along nicely until I hit this one.

I don't see anywhere in this article that refers to BlogPostContext.cs  , where is the project solution.

best regards
Comment posted by Sumit on Friday, March 16, 2012 11:29 AM
Hi Patrick,
My bad, we should have linked to the previous post and code. You can start off with the code here:
This code is the Non-DI version.

The Final code for this article is linked at the bottom of this post.
Hope this helps,
Thanks and Regards,
Comment posted by angel on Sunday, May 6, 2012 6:08 PM
very nice article, please I wish an article about Ninject and really hard found documentation...thanks
Comment posted by Luis Ferreira on Friday, May 25, 2012 7:38 AM

Thank you for a very clear article. Some people know a lot but are unable to share. You have a very didactic approach.

Thanks again,
Comment posted by Reinard Mavronicolas on Friday, June 1, 2012 6:39 AM

Thank you for this example. Very good illustration!

Don't know if you've noticed, but there's one small mistake in your CompositionRoot code example. When you instantiate an instance of the BlogRepositoryType, your casting it to BlogPostRepository. It should be IBlogPostRepository?

Comment posted by Amit on Wednesday, August 1, 2012 12:00 PM
Hi Sumit, You are a savior :)
I have a question when you have a busines layer separate from domain layer along with View and data access layers. Would you still make your View layer dependent on business layer? or you would implement DI for your business layer as well?

Comment posted by Amit on Wednesday, August 1, 2012 12:18 PM
Hi Sumit, You are a savior :)
I have a question when you have a busines layer separate from domain layer along with View and data access layers. Would you still make your View layer dependent on business layer? or you would implement DI for your business layer as well?

Comment posted by Nuno Agapito on Saturday, August 11, 2012 8:06 PM

Nice post, it helped me a lot figuring out how to implement my controllers.
But, seems you might have a little problem with your example!

When you instantiate you CompositionRoot at the application start, you create a context singleton that will be used during all the lifetime of your application. Shouldnt the data access context be recreated at every request?

Also, you are instantiating and storing the controllers on a dictionary and when you need to return a controller, you dont return a new instance, you always return the same one and that might get some ugly if the internal state of the controller isnt somehow reseted...

N. Agapito
Comment posted by Sumit on Sunday, August 12, 2012 3:35 PM
Hello Amit,
No harm in programming to interfaces and passing dependencies in at any layer. If you are going that deep, suggest using an IoC container to help you with the lifecycle management of dependencies.

Hello Agapito,
What's stored in the dictionary is a lambda expression. The expression is creates a new Controller every time you access the singleton dictionary by the key. So to answer you question no, it's not the same instance it's a new instance every time. Put a breakpoint in the constructor and see for yourself.

Next the Repository is created once, but the DbContext is created for every call so we are safe there too.

Hope this helps,
Comment posted by Manoj SIngh on Sunday, September 9, 2012 5:53 AM
      I have Completed MCA 1i 2009 There is 3 yr of gap,But Now Iwant to come Back in C# .net technology .What should I do now
And I complete core .net presently.
plz suggest me.                   your faithful  manoj Singh
Comment posted by chandra on Friday, October 12, 2012 6:09 AM
Its awesome, thank you very much......................
Comment posted by Tohid Azizi on Friday, October 19, 2012 10:34 AM

Thank you for the great article.

Can I find a similar article about how DI works in MVC 4 WEB API?

Your code works great with "Controller" inherited classes but not with "ApiController"s.

For some reason I prefer not to use 3rd party DI (such as Ninject) and want to write the code myself.

Thank you.
Comment posted by Tohid Azizi on Monday, October 22, 2012 3:43 PM
I've also written my question in StackOverflow:
P l e a s e  Somebody help :)
Comment posted by Sumit on Tuesday, October 23, 2012 5:35 AM
Hi Tohid,
Apologies for the delay in response. I am currently on a 'vacation'. I see you already have an answered question on SO. I can further point you to my ChirpyR application on GitHub at

Checkout the WebApiDependencyResolver.cs and how it is hooked up in the CompositionRoot.cs

Hope this helps,
Comment posted by Sumit on Tuesday, October 23, 2012 5:48 AM
Okay, my previous answer is a little 'old' and the SO answer points to an article by the original inspiration behind this post, Mark Seemann. Mark in his post here
advocates against use of IDependencyResolver since it uses the service locator (anti) pattern, which primarily results in the controller not having a well defined context.

Mark's answer is to use custom instance of IHttpControllerActivator. Please refer to his blog for the complete description.
Comment posted by TOHID AZIZI on Tuesday, October 23, 2012 10:03 AM
<b>Update to my question:</b>
I've received this answer:
which leads me to this article:
So by creating an implementation of IHttpControllerActivator and replacing the ServicesContainer by using :

Is there any better way?

Comment posted by Ashikur rahman on Tuesday, November 13, 2012 10:52 AM
i believe that it helps me more
i want a link that will helps me when need
Comment posted by Vetrivel on Friday, January 25, 2013 6:53 AM
Its very very nice article. it clears my doubts on DI. Thanks a lot
Comment posted by Greg Poirson on Friday, March 15, 2013 10:33 AM
Very nice
Comment posted by mohammad sepahvand on Wednesday, May 8, 2013 5:25 AM
brilliant article, well done.
Comment posted by Kaushal on Monday, September 16, 2013 12:38 PM
Hello Sumit,
Thanks for sharing such a nice article. I am trying to get some small architecture for MVC using DI. Here I will be needing to create a service class in Domain layer because I am having a bit business logic that should not be done/burdened at Data layer. I followed the article, but created a Service class "BlogService" at Domain layer. Now, I understand that the IBlogRepository (which exists at Domain layer) interface will be implemented by this "BlogService". IS that correct? Then I am having some doubts.
[1] If "BlogService" will implement IBlogRepository interface then at BlogController; I will have to create an instance of BlogService class to call the IBlogReposiroty methods. Is that correct? And if yes, then will it not be against DI?
[2] If I use BlogService Instance at controller, then I understand that parametrized Controller constructor (BlogController) will not be  required. Is it correct? Because I am instantiating BlogService class object directly in BlogController.
[3] Should I create a separate Interface for CRUD/data access level operations in Data layer?
Apologies to my silly questions. I am trying to adapt these things very lately. Please reply when you are available. Thank you my friend.
Comment posted by JOhn on Thursday, October 17, 2013 3:19 PM

Post your comment
E-mail: (Will not be displayed)
Insert Cancel